前言
前文介紹了一些基本思路,那麼這裡介紹一下,服務如何與配置檔案配合。
正文
服務:
public interface ISelfService
{
void ShowLog();
}
public class SelfService : ISelfService
{
public ILogger<SelfService> _Logger;
public SelfService(ILogger<SelfService> logger)
{
_Logger = logger;
}
public void ShowLog()
{
_Logger.LogInformation("I am a log.");
}
}
配置:
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"Console": {
"LogLevel": {
"Default": "Information",
"Program": "Trace",
"loggerObj": "Debug"
}
}
}
}
測試程式碼:
static void Main(string[] args)
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("appsettings.json",optional:false,reloadOnChange:true);
var config = configurationBuilder.Build();
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IConfiguration>(p=>config);
serviceCollection.AddSingleton<ISelfService,SelfService>();
serviceCollection.AddLogging(builder =>
{
builder.AddConfiguration(config.GetSection("Logging"));
builder.AddConsole();
});
IServiceProvider service = serviceCollection.BuildServiceProvider();
var selfService = service.GetService<ISelfService>();
selfService.ShowLog();
Console.ReadKey();
}
結果:
那麼如何要配置單個服務的Logger級別呢?
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"Console": {
"LogLevel": {
"Default": "Information",
"Program": "Trace",
"loggerObj": "Debug",
"ConfigureDemo.SelfService": "Error"
}
}
}
}
設定這個ConfigureDemo.SelfService的值就可以。為什麼這樣呢?
看ILogger 的實現類Logger:
public Logger(ILoggerFactory factory)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
_logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T), includeGenericParameters: false, nestedTypeDelimiter: '.'));
}
這裡會建立一個預設的TypeNameHelper.GetTypeDisplayName(typeof(T))的logger例項名字。
這個會獲取到全名,故而設定好全名,那麼會去使用這個配置。
我們一般列印log的時候,要去輸出時間,建議這樣寫:
public class SelfService : ISelfService
{
public ILogger<SelfService> _Logger;
public SelfService(ILogger<SelfService> logger)
{
_Logger = logger;
}
public void ShowLog()
{
_Logger.LogInformation("I am a log.",DateTime.Now);
}
}
效果如下:
_Logger.LogInformation("I am a log.",DateTime.Now);
這樣寫的好處因為我們的log有過濾機制,如果我們過濾不輸出,那麼"I am a log."和DateTime.Now就不會去做拼接執行。
這也是一種延遲思想的表現。
結
以上只是個人整理,如有錯誤,望請指點。
下一節日誌作用域