asp.net core NLog将日志写到文件

1、安装Nlog包

    1、1: NLog.Web.AspNetCore

        1、2:NLog

2、在项目添加nlog.config文件

asp.net core NLog将日志写到文件_第1张图片

 2.1、nlog.config 




  
  
    
    


    

    
  

  
    
    

    
    
    
  

3、修改Program.cs中Main方法

 

public static void Main(string[] args)
        {
            //添加Nlog日志
            NLog.Web.NLogBuilder.ConfigureNLog("Config/nlog.config").GetCurrentClassLogger();
            CreateHostBuilder(args).Build().Run();
        }

 在IHostBuilder方法中添加UseNLog()

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup();
                })
                .UseNLog();

 

 

4、Controller 调用Nlog 方法

public class BlogController : Controller
    {
        private TestDBContext dBContext;
        private readonly ILogger logger;
        public BlogController(TestDBContext _dBContext, ILogger  _logger)
        {
            dBContext = _dBContext;
            logger = _logger;
        }

        public IActionResult Index()
        {
            logger.LogInformation("你访问了首页55555");
            logger.LogWarning("警告信息55555");
            logger.LogError("错误信息55555");

            var list = dBContext.Blog.Select(a => new BlogViewModel() {
                CreateTime = a.CreateTime,
                Id = a.BlogId,
                Title = a.Title,
                Url = a.Url
            }).ToList();
            return View(list);
        }
}

 

6、运行项目成功,查看log

log 目录在bin 目录下 

asp.net core NLog将日志写到文件_第2张图片

asp.net core NLog将日志写到文件_第3张图片

 

事半功倍

你可能感兴趣的:(dotnet)