web-dev-qa-db-fra.com

Configuration de Serilog RollingFile avec appsettings.json

J'essaie de configurer Serilog pour un projet .NET Core. Voici ce que j'ai dans mon appsettings.json:

 "Serilog": 
{
    "MinimumLevel": "Verbose",
    "Enrich": ["FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId"],
    "WriteTo": [
      { "Name": "RollingFile",
        "Args": {
          "pathFormat": "C:/Logfiles/testapp/log-{Date}.json",
          "textFormatter": "JsonFormatter",
          "fileSizeLimitBytes": 2147483648,
          "retainedFileCountLimit": 5
        }
      }
    ]
  }

Le problème que je vois est que JsonFormatter n'est pas récupéré, et à la place j'obtiens des entrées en utilisant le formateur de texte par défaut. J'ai essayé d'utiliser "formatter": "JsonFormatter", mais a obtenu le même résultat.

Tout fonctionne bien si je configure Serilog dans le code:

var jsonSink = new RollingFileSink(config["Logger:FilePath"], new JsonFormatter(), 2147483648, 5);

var logger = new Serilog.LoggerConfiguration().WriteTo.Sink(jsonSink);

Voici la section pertinente de mon project.json:

"Serilog": "2.2.1",
"Serilog.Extensions.Logging": "1.1.0",
"Serilog.Sinks.Literate": "2.0.0",
"Serilog.Sinks.Seq": "2.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Serilog.Enrichers.Thread": "2.0.0",
"Serilog.Enrichers.Process": "2.0.0",
"Serilog.Sinks.ColoredConsole": "2.0.0",
"Serilog.Settings.Configuration": "2.2.0"

Des conseils sur la façon de faire fonctionner cela?

Merci!

14
Alexander

L'argument formatter doit être un nom de type complet. Essayer:

"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
12
Nicholas Blumhardt

Les oeuvres suivantes:

var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "C:\\logs\\log-{Date}.txt"),
                            outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}")
            //.ReadFrom.Configuration(Configuration)
            .CreateLogger();

        Log.Logger.Information("test");

Les éléments suivants fonctionnent également (affichant uniquement la partie CreateLogger):

Log.Logger = new LoggerConfiguration()
            //.MinimumLevel.Debug()
            //.WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "C:\\logs\\log-{Date}.txt"),
            //                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}")
            .ReadFrom.Configuration(Configuration)
            .CreateLogger();

Le fichier appsettings.json (la section pertinente ici est Serilog):

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Serilog": {
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "C:\\logs\\log-{Date}.txt",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}"
        }
      }
    ]
  }
}

Les packages NuGet dans project.json:

  • "Serilog": "2.3.0",
  • "Serilog.Extensions.Logging": "1.3.1",
  • "Serilog.Sinks.RollingFile": "3.2.0",
  • "Serilog.Sinks.File": "3.1.1",
  • "Serilog.Settings.Configuration": "2.2.0"

Mon framework cible est net452.

7
Jeremy Ray Brown

La configuration suivante fonctionne:

"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": "Information", 
"WriteTo": [
  {
    "Name": "Console",
    "Args": {
      "outputTemplate": "===> {Timestamp:HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"
    }
  },
  {
    "Name": "RollingFile",
    "Args": {
      "pathFormat": "Logs\\log-{Date}.json",
      "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
      "fileSizeLimitBytes": 104857600
    }
  }


 ]
}

Dans Program.cs:

public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
            .AddEnvironmentVariables()
            .Build();    
public static void Main(string[] args)
            {
                Log.Logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(Configuration)
                    .CreateLogger();
    ...
    }

et

public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseConfiguration(Configuration)
                .ConfigureLogging(log => { log.AddSerilog(Log.Logger); })
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

Et injectez l'enregistreur dans votre contrôleur:

public class UsersController : ControllerBase
{
private readonly ILogger<UsersController> _logger;

  public UsersController(ILogger<UsersController> logger)
     {
      _logger = logger;        
     }
     //your code
    }

Exemple de résultat que j'ai obtenu:

{
"@t": "2019-04-12T14:03:08.2789776Z",
"@mt": "GetUserMessages()=> ",
"@r": [
    "000117"
],
"Elapsed": 117,
"SourceContext": "MyProject.Web.Controllers.UsersController",
"ActionId": "1b8bc4b9-5858-415b-ab4e-56ba14a5a1ca",
"ActionName": "MyProject.Web.Controllers.UsersController.GetUserMessages (MyProject.Web)",
"RequestId": "0HLLVSDFSA43ES:00000001",
"RequestPath": "/TestAppId/messages",
"CorrelationId": null,
"ConnectionId": "0HLLVSDFSA43ES"
}
1
Dmitry