2017-03-18 22 views
0

在我appsettings.json我已經寫了:如何使用Serilog的ReadFrom.KeyValuePairs方法?

{ 
    "Logging": { 
     "PathLogsFile": "./Logs", 
     "IncludeScopes": false, 
     "LogLevel": { 
      "Default": "Debug", 
      "System": "Information", 
      "Microsoft": "Information" 
     } 
    } 
} 

,在我startup.cs文件中構造

var pathLogsFile = Configuration["Logging:PathLogsFile"];    
var logLevelApp = Configuration.GetSection("Logging:LogLevel:Default"); 

Log.Logger = new LoggerConfiguration()   
    .ReadFrom.KeyValuePairs(new List<KeyValuePair<string, string>>() 
     { 
      new KeyValuePair<string, string>(logLevelApp.Key, logLevelApp.Value)       
     }.ToDictionary(x => x.Key, x => x.Value)) 
    .Enrich.FromLogContext() 
    .WriteTo.Logger(lc => lc 
     .Filter.ByIncludingOnly(evt => evt.Level == Serilog.Events.LogEventLevel.Error) 
     .WriteTo.RollingFile(Path.Combine(pathLogsFile, "error-{Date}.log"))) 
    .WriteTo.Logger(lc => lc 
     .Filter.ByIncludingOnly(evt => evt.Level >= Serilog.Events.LogEventLevel.Debug) 
     .WriteTo.RollingFile(Path.Combine(pathLogsFile, "log-{Date}.log"))) 
    .CreateLogger(); 

但是從AppSettings的讀不在最低水平。 任何想法?我該如何解決?

+0

請不要強制標籤進入標題。閱讀關於如何正確使用標籤的幫助中心文章http://stackoverflow.com/help/tagging – Tseng

+0

對不起@Tseng – FabioBit

回答

1

我相信這是你在找什麼

這裏是serilog配置的appsettings.json樣本

{ 
    "Serilog": { 
    "Using": ["Serilog.Sinks.Literate"], 
    "MinimumLevel": "Debug", 
    "WriteTo": [ 
     { "Name": "LiterateConsole" }, 
     { "Name": "File", "Args": { "path": "%TEMP%\\Logs\\serilog-configuration-sample.txt" } } 
    ], 
    "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"], 
    "Properties": { 
     "Application": "Sample" 
    } 
    } 
} 

startup.cs

var configuration = new ConfigurationBuilder() 
     .AddJsonFile("appsettings.json") 
     .Build(); 

var logger = new LoggerConfiguration() 
     .ReadFrom.Configuration(configuration) 
     .CreateLogger(); 
+0

沒有辦法從我的appsettings.json獲取Logging部分的值(這是由'dotnet new mvc -au None -f netcoreapp1.1'命令創建),然後在** startup.cs **中使用'ReadFrom.KeyValuePairs()'方法? – FabioBit

+0

Serilog.Settings.Configuration包中,ReadFrom.Configuration()讓我們從appsettings.json中提取相同的信息。唯一需要確定的是appsettings.json上有一個serilog部分 – CPR43

+0

如何將我的代碼從Log.Logger = new LoggerConfiguration()'到appsettings.json在一個serilog節中? – FabioBit