时间:2021-07-01 10:21:17 帮助过:11人阅读
3.将nlog.config复制到bin文件夹
4.设置数据库(我使用的是ef code first方式创建数据表)
1 using System; 2 3 namespace Apps.Models 4 { 5 public class ApplicationLog 6 { 7 public int Id { get; set; } 8 public string Application { get; set; } 9 public DateTime Logged { get; set; } 10 public string Level { get; set; } 11 public string Message { get; set; } 12 public string Logger { get; set; } 13 public string Callsite { get; set; } 14 public string Exception { get; set; } 15 } 16 }
1 protected override void OnModelCreating(ModelBuilder builder) 2 { 3 builder.Entity<ApplicationLog>(m => 4 { 5 m.ToTable("Log"); 6 m.HasKey(c => c.Id); 7 m.Property(c => c.Application).IsRequired().HasMaxLength(50); 8 m.Property(c => c.Level).IsRequired().HasMaxLength(50); 9 m.Property(c => c.Message).IsRequired(); 10 m.Property(c => c.Logger).HasMaxLength(250); 11 }); 12 }
5.在startup.cs文件中添加:
1 using NLog.Extensions.Logging; 2 using NLog.Web; 3 4 public Startup(IHostingEnvironment env) 5 { 6 env.ConfigureNLog("nlog.config"); 7 } 8 9 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 10 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 11 { 12 13 14 loggerFactory.AddNLog(); 15 16 app.AddNLogWeb(); 17 LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection"); 18 LogManager.Configuration.Variables["configDir"] = Configuration.GetSection("LogFilesDir").Value; 19 }
6.appsettings.json
"ConnectionStrings": { "DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=logdb;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" }, "LogFilesDir": "c:\\temp\\nlog\\logfiles"
7.然后就可以记录日志了
1 public class HomeController :Controller { 2 private readonly ILogger _logger; 3 4 public HomeController(ILoggerFactory loggerFactory) { 5 _logger = loggerFactory.CreateLogger<HomeController>(); 6 } 7 public IActionResult Index() { 8 _logger.LogInformation("你访问了首页"); 9 _logger.LogWarning("警告信息"); 10 _logger.LogError("错误信息"); 11 return View(); 12 } 13 }
ASP.NET Core使用NLog记录日志到Microsoft Sql Server
标签:oge alt manager .sql conf rust max 分享 elb