我正在尝试为.NET Core项目配置Serilog。这是我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
}
}
]
}
我看到的问题是没有选择JsonFormatter
,而是使用默认文本格式化程序获取条目。我尝试使用"formatter": "JsonFormatter"
,但得到了相同的结果。
如果我在代码中配置Serilog,一切正常:
var jsonSink = new RollingFileSink(config["Logger:FilePath"], new JsonFormatter(), 2147483648, 5);
var logger = new Serilog.LoggerConfiguration().WriteTo.Sink(jsonSink);
以下是我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"
有关如何使其工作的任何指示?
谢谢!
答案 0 :(得分:10)
formatter
参数必须是完全限定的类型名称。尝试:
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
答案 1 :(得分:5)
以下作品:
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");
以下也有效(仅显示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();
appsettings.json文件(这里的相关部分是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}"
}
}
]
}
}
project.json中的NuGet包:
我的目标框架是net452。
答案 2 :(得分:1)
以下配置有效:
"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
}
}
]
}
在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();
...
}
和
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseConfiguration(Configuration)
.ConfigureLogging(log => { log.AddSerilog(Log.Logger); })
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
然后将记录器注入到您的控制器中
public class UsersController : ControllerBase
{
private readonly ILogger<UsersController> _logger;
public UsersController(ILogger<UsersController> logger)
{
_logger = logger;
}
//your code
}
我得到的结果示例:
{
"@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"
}
答案 3 :(得分:0)
这对我来说很好用。不再支持“RollingFile”,因此“File”和“pathFormat”只是“path”
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Debug",
"System": "Debug"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "===> {Timestamp:HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "C:\\Temp\\Logs\\log-appstngs.log",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}",
"rollOnFileSizeLimit": true,
"fileSizeLimitBytes": 4194304,
"retainedFileCountLimit": 10,
"rollingInterval": "Minute"
}
}
]
},