Skip to content
This repository has been archived by the owner on Dec 8, 2018. It is now read-only.

Add logger extensions with event ids #405

Merged
merged 3 commits into from
Sep 15, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.Internal;
using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.Views;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
Expand Down Expand Up @@ -115,15 +116,15 @@ public virtual async Task Invoke(HttpContext httpContext)

if (context == null)
{
_logger.LogError(Strings.FormatDatabaseErrorPageMiddleware_ContextNotRegistered(contextType.FullName));
_logger.ContextNotRegisteredDatabaseErrorPageMiddleware(contextType.FullName);
}
else
{
var relationalDatabaseCreator = context.GetService<IDatabaseCreator>() as IRelationalDatabaseCreator;

if (relationalDatabaseCreator == null)
{
_logger.LogDebug(Strings.DatabaseErrorPage_NotRelationalDatabase);
_logger.NotRelationalDatabase();
}
else
{
Expand Down Expand Up @@ -164,10 +165,7 @@ var pendingMigrations
}
catch (Exception e)
{
_logger.LogError(
eventId: 0,
exception: e,
message: Strings.DatabaseErrorPageMiddleware_Exception);
_logger.DatabaseErrorPageMiddlewareException(e);
}

throw;
Expand All @@ -176,13 +174,13 @@ var pendingMigrations

private bool ShouldDisplayErrorPage(Exception exception)
{
_logger.LogDebug(Strings.FormatDatabaseErrorPage_AttemptingToMatchException(exception.GetType()));
_logger.AttemptingToMatchException(exception.GetType());

var lastRecordedException = _localDiagnostic.Value.Exception;

if (lastRecordedException == null)
{
_logger.LogDebug(Strings.DatabaseErrorPage_NoRecordedException);
_logger.NoRecordedException();

return false;
}
Expand All @@ -196,12 +194,12 @@ private bool ShouldDisplayErrorPage(Exception exception)

if (!match)
{
_logger.LogDebug(Strings.DatabaseErrorPage_NoMatch);
_logger.NoMatch();

return false;
}

_logger.LogDebug(Strings.DatabaseErrorPage_Matched);
_logger.Matched();

return true;
}
Expand All @@ -219,17 +217,17 @@ void IObserver<KeyValuePair<string, object>>.OnNext(KeyValuePair<string, object>
switch (keyValuePair.Value)
{
case DbContextErrorEventData contextErrorEventData:
{
_localDiagnostic.Value.Hold(contextErrorEventData.Exception, contextErrorEventData.Context.GetType());
{
_localDiagnostic.Value.Hold(contextErrorEventData.Exception, contextErrorEventData.Context.GetType());

break;
}
break;
}
case DbContextTypeErrorEventData contextTypeErrorEventData:
{
_localDiagnostic.Value.Hold(contextTypeErrorEventData.Exception, contextTypeErrorEventData.ContextType);
{
_localDiagnostic.Value.Hold(contextTypeErrorEventData.Exception, contextTypeErrorEventData.ContextType);

break;
}
break;
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.Internal
{
internal static class DiagnosticsEntityFrameworkCoreLoggerExtensions
{
// MigrationsEndPointMiddleware
private static readonly Action<ILogger, Exception> _noContextType = LoggerMessage.Define(
LogLevel.Error,
new EventId(1, "NoContextType"),
"No context type was specified. Ensure the form data from the request includes a contextTypeName value, specifying the context to apply migrations for.");

private static readonly Action<ILogger, string, Exception> _invalidContextType = LoggerMessage.Define<string>(
LogLevel.Error,
new EventId(2, "InvalidContextType"),
"The context type '{ContextTypeName}' could not be loaded. Ensure this is the correct type name for the context you are trying to apply migrations for.");

private static readonly Action<ILogger, string, Exception> _contextNotRegistered = LoggerMessage.Define<string>(
LogLevel.Error,
new EventId(3, "ContextNotRegistered"),
"The context type '{ContextTypeName}' was not found in services. This usually means the context was not registered in services during startup. You probably want to call AddScoped<>() inside the UseServices(...) call in your application startup code.");

private static readonly Action<ILogger, string, Exception> _requestPathMatched = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(4, "RequestPathMatched"),
"Request path matched the path configured for this migrations endpoint({RequestPath}). Attempting to process the migrations request.");

private static readonly Action<ILogger, string, Exception> _applyingMigrations = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(5, "ApplyingMigrations"),
"Request is valid, applying migrations for context '{ContextTypeName}'");

private static readonly Action<ILogger, string, Exception> _migrationsApplied = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(6, "MigrationsApplied"),
"Migrations successfully applied for context '{ContextTypeName}'.");

private static readonly Action<ILogger, string, Exception> _migrationsEndPointMiddlewareException = LoggerMessage.Define<string>(
LogLevel.Error,
new EventId(7, "MigrationsEndPointException"),
"An error occurred while applying the migrations for '{ContextTypeName}'. See InnerException for details:");

// DatabaseErrorPageMiddleware
private static readonly Action<ILogger, Type, Exception> _attemptingToMatchException = LoggerMessage.Define<Type>(
LogLevel.Debug,
new EventId(1, "AttemptingToMatchException"),
"{ExceptionType} occurred, checking if Entity Framework recorded this exception as resulting from a failed database operation.");

private static readonly Action<ILogger, Exception> _noRecordedException = LoggerMessage.Define(
LogLevel.Debug,
new EventId(2, "NoRecordedException"),
"Entity Framework did not record any exceptions due to failed database operations. This means the current exception is not a failed Entity Framework database operation, or the current exception occurred from a DbContext that was not obtained from request services.");

private static readonly Action<ILogger, Exception> _noMatch = LoggerMessage.Define(
LogLevel.Debug,
new EventId(3, "NoMatchFound"),
"The current exception (and its inner exceptions) do not match the last exception Entity Framework recorded due to a failed database operation. This means the database operation exception was handled and another exception occurred later in the request.");

private static readonly Action<ILogger, Exception> _matched = LoggerMessage.Define(
LogLevel.Debug,
new EventId(4, "MatchFound"),
"Entity Framework recorded that the current exception was due to a failed database operation. Attempting to show database error page.");

private static readonly Action<ILogger, string, Exception> _contextNotRegisteredDatabaseErrorPageMiddleware = LoggerMessage.Define<string>(
LogLevel.Error,
new EventId(5, "ContextNotRegistered"),
"The context type '{ContextTypeName}' was not found in services. This usually means the context was not registered in services during startup. You probably want to call AddScoped<>() inside the UseServices(...) call in your application startup code. Skipping display of the database error page.");

private static readonly Action<ILogger, Exception> _notRelationalDatabase = LoggerMessage.Define(
LogLevel.Debug,
new EventId(6, "NotRelationalDatabase"),
"The target data store is not a relational database. Skipping the database error page.");

private static readonly Action<ILogger, Exception> _databaseErrorPageMiddlewareException = LoggerMessage.Define(
LogLevel.Error,
new EventId(7, "DatabaseErrorPageException"),
"An exception occurred while calculating the database error page content. Skipping display of the database error page.");

public static void NoContextType(this ILogger logger)
{
_noContextType(logger, null);
}

public static void InvalidContextType(this ILogger logger, string contextTypeName)
{
_invalidContextType(logger, contextTypeName, null);
}

public static void ContextNotRegistered(this ILogger logger, string contextTypeName)
{
_contextNotRegistered(logger, contextTypeName, null);
}

public static void RequestPathMatched(this ILogger logger, string requestPath)
{
_requestPathMatched(logger, requestPath, null);
}

public static void ApplyingMigrations(this ILogger logger, string contextTypeName)
{
_applyingMigrations(logger, contextTypeName, null);
}

public static void MigrationsApplied(this ILogger logger, string contextTypeName)
{
_migrationsApplied(logger, contextTypeName, null);
}

public static void MigrationsEndPointMiddlewareException(this ILogger logger, string context, Exception exception)
{
_migrationsEndPointMiddlewareException(logger, context, exception);
}

public static void AttemptingToMatchException(this ILogger logger, Type exceptionType)
{
_attemptingToMatchException(logger, exceptionType, null);
}

public static void NoRecordedException(this ILogger logger)
{
_noRecordedException(logger, null);
}

public static void NoMatch(this ILogger logger)
{
_noMatch(logger, null);
}

public static void Matched(this ILogger logger)
{
_matched(logger, null);
}

public static void NotRelationalDatabase(this ILogger logger)
{
_notRelationalDatabase(logger, null);
}

public static void ContextNotRegisteredDatabaseErrorPageMiddleware(this ILogger logger, string contextTypeName)
{
_contextNotRegisteredDatabaseErrorPageMiddleware(logger, contextTypeName, null);
}

public static void DatabaseErrorPageMiddlewareException(this ILogger logger, Exception exception)
{
_databaseErrorPageMiddlewareException(logger, exception);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -66,29 +67,29 @@ public virtual async Task Invoke(HttpContext context)

if (context.Request.Path.Equals(_options.Path))
{
_logger.LogDebug(Strings.FormatMigrationsEndPointMiddleware_RequestPathMatched(context.Request.Path));
_logger.RequestPathMatched(context.Request.Path);

var db = await GetDbContext(context, _logger);

if (db != null)
{
try
{
_logger.LogDebug(Strings.FormatMigrationsEndPointMiddleware_ApplyingMigrations(db.GetType().FullName));
_logger.ApplyingMigrations(db.GetType().FullName);

db.Database.Migrate();

context.Response.StatusCode = (int)HttpStatusCode.NoContent;
context.Response.Headers.Add("Pragma", new[] { "no-cache" });
context.Response.Headers.Add("Cache-Control", new[] { "no-cache" });

_logger.LogDebug(Strings.FormatMigrationsEndPointMiddleware_Applied(db.GetType().FullName));
_logger.MigrationsApplied(db.GetType().FullName);
}
catch (Exception ex)
{
var message = Strings.FormatMigrationsEndPointMiddleware_Exception(db.GetType().FullName) + ex;

_logger.LogError(message);
_logger.MigrationsEndPointMiddlewareException(db.GetType().FullName, ex);

throw new InvalidOperationException(message, ex);
}
Expand All @@ -107,7 +108,7 @@ private static async Task<DbContext> GetDbContext(HttpContext context, ILogger l

if (string.IsNullOrWhiteSpace(contextTypeName))
{
logger.LogError(Strings.MigrationsEndPointMiddleware_NoContextType);
logger.NoContextType();

await WriteErrorToResponse(context.Response, Strings.MigrationsEndPointMiddleware_NoContextType);

Expand All @@ -120,7 +121,7 @@ private static async Task<DbContext> GetDbContext(HttpContext context, ILogger l
{
var message = Strings.FormatMigrationsEndPointMiddleware_InvalidContextType(contextTypeName);

logger.LogError(message);
logger.InvalidContextType(contextTypeName);

await WriteErrorToResponse(context.Response, message);

Expand All @@ -133,7 +134,7 @@ private static async Task<DbContext> GetDbContext(HttpContext context, ILogger l
{
var message = Strings.FormatMigrationsEndPointMiddleware_ContextNotRegistered(contextType.FullName);

logger.LogError(message);
logger.ContextNotRegistered(contextType.FullName);

await WriteErrorToResponse(context.Response, message);

Expand Down
Loading