前言
前文介绍了一些基本思路,那么这里介绍一下,服务如何与配置文件配合。
正文
服务:
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就不会去做拼接执行。
这也是一种延迟思想的表现。
结
以上只是个人整理,如有错误,望请指点。
下一节日志作用域