You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
3.2 KiB
C#

5 years ago
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
5 years ago
using Microsoft.Extensions.DependencyInjection;
5 years ago
using Microsoft.Extensions.Logging;
5 years ago
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Debug;
5 years ago
namespace LogStudy.WebApp
{
public class Program
{
public static void Main(string[] args)
{
5 years ago
var host = CreateWebHostBuilder(args).Build();
//启动检查:使用日志
var logger = host.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("检查数据库连接");
logger.LogDebug(new EventId(1000,"事件名"),"检查缓存{id}",222);
//少提供一个参数
logger.LogInformation("1001","检查MQ{id}{name}",3333);
host.Run();
5 years ago
}
5 years ago
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var webBuilder = WebHost.CreateDefaultBuilder(args)
//配置日志
.ConfigureLogging((hostbuildContext, logBuild) =>
{
//CreateDefaultBuilder 默认注册了日志组件:
//使用appsettings.环境变量.json 的Logging配置节
//默认添加了以下提供程序Console、 Debug、EventSource
//详情可以查看源代码
//本方法ConfigureLogging重新配置日志
//配置信息
var config = hostbuildContext.Configuration;
//环境变量
var ev = hostbuildContext.HostingEnvironment;
//注入服务
var service=logBuild.Services;
logBuild
//自定义配置信息
.AddConfiguration(config.GetSection("Logging"))
//添加Console提供程序
.AddConsole()
//添加Debug提供程序
.AddDebug()
//添加EventLog提供程序
.AddEventLog()
//添加EventSourceLogger提供程序:EWT
.AddEventSourceLogger()
//添加TraceSource提供程序
.AddTraceSource("NetCoreDemo")
//设置最小默认日志级别
.SetMinimumLevel(LogLevel.Information)
//添加筛选器:会覆盖上面配置信息
.AddFilter("System", LogLevel.Debug) //不指定提供程序,则应用与全部
.AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Trace);//只作用于指定的提供程序 DebugLoggerProvider
//以下方式可以使用第三方日志组件如Nlog、Log4net等
//.ClearProviders()
//.AddProvider(null)
})
.UseStartup<Startup>();
return webBuilder;
}
5 years ago
}
}