当前位置:   article > 正文

Core使用NLog记录日志_nlog.logmanager.configuration.variables

nlog.logmanager.configuration.variables

一、新建日志表

  1. CREATE TABLE [dbo].[Sys_Log](
  2. [Id] [varchar](50) NOT NULL CONSTRAINT [DF_Sys_Log_Id] DEFAULT (newid()),
  3. [Application] [varchar](200) NULL,
  4. [Logger] [varchar](200) NULL,
  5. [Level] [varchar](50) NULL,
  6. [Message] [varchar](max) NULL,
  7. [Exception] [varchar](max) NULL,
  8. [Callsite] [varchar](200) NULL,
  9. [CreateDate] [datetime] NULL,
  10. CONSTRAINT [PK_SYS_LOG] PRIMARY KEY CLUSTERED
  11. (
  12. [Id] ASC
  13. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  14. ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  15. GO
  16. SET ANSI_PADDING OFF
  17. GO
  18. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'主键(默认值是newid())' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Log', @level2type=N'COLUMN',@level2name=N'Id'
  19. GO
  20. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日志所属应用' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Log', @level2type=N'COLUMN',@level2name=N'Application'
  21. GO
  22. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日志所属类' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Log', @level2type=N'COLUMN',@level2name=N'Logger'
  23. GO
  24. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日志级别' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Log', @level2type=N'COLUMN',@level2name=N'Level'
  25. GO
  26. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日志信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Log', @level2type=N'COLUMN',@level2name=N'Message'
  27. GO
  28. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'异常信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Log', @level2type=N'COLUMN',@level2name=N'Exception'
  29. GO
  30. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日志所属方法' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Log', @level2type=N'COLUMN',@level2name=N'Callsite'
  31. GO
  32. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Log', @level2type=N'COLUMN',@level2name=N'CreateDate'
  33. GO
  34. EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'系统异常日志表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Log'
  35. GO

二、准备配置文件

设置<parameter>节点中的layout="${event-properties:item=callsite}" ,可以自定义日志表中某列的值。
如果设置了layout="${event-properties:item=callsite}",但是没有通过LogEventInfo.Properties[""]对参数赋值,那数据库中本条数据对应的字段值就为空。

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. autoReload="true"
  5. internalLogLevel="Warn"
  6. internalLogFile="c:\temp\internal-nlog.txt">
  7. <!-- 加载ASP.NET Core插件 -->
  8. <extensions>
  9. <add assembly="NLog.Web.AspNetCore"/>
  10. </extensions>
  11. <!-- 输出目的地 -->
  12. <targets>
  13. <!-- 输出到文件,这个文件记录所有日志 -->
  14. <target xsi:type="File" name="allfile" fileName="d:\temp\nlog-all-${shortdate}.log"
  15. layout="${longdate} | ${event-properties:item=EventId.Id} | ${logger} | ${uppercase:${level}} | ${message} ${exception}" />
  16. <!-- 另外一个日志记录文件,户口也跳过Microsoft开头相关日志信息 -->
  17. <target xsi:type="File" name="ownFile-web" fileName="d:\temp\nlog-own-${shortdate}.log"
  18. layout="${longdate} | ${event-properties:item=EventId.Id} | ${logger} | ${uppercase:${level}} | ${message} ${exception} | ${aspnet-mvc-controller} | ${aspnet-mvc-action}" />
  19. <!-- write to the void aka just remove -->
  20. <target xsi:type="Null" name="blackhole" />
  21. <target name="database" xsi:type="Database">
  22. <connectionString>${var:connectionString}</connectionString>
  23. <commandText>
  24. insert into dbo.Sys_Log (
  25. Application, CreateDate, Level, Message,Logger, Callsite, Exception
  26. ) values (
  27. @Application, @CreateDate, @Level, @Message,@Logger, @Callsite, @Exception
  28. );
  29. </commandText>
  30. <parameter name="@application" layout="${event-properties:item=application}" />
  31. <parameter name="@createDate" layout="${date}" />
  32. <parameter name="@level" layout="${level}" />
  33. <parameter name="@message" layout="${message}" />
  34. <parameter name="@logger" layout="${logger}" />
  35. <parameter name="@callSite" layout="${event-properties:item=callsite}" />
  36. <parameter name="@exception" layout="${exception:format=toString,Data}" />
  37. </target>
  38. </targets>
  39. <!-- 写入目的地的规则 -->
  40. <rules>
  41. <!--全部记录,包括Microsoft开头的相关日志信息-->
  42. <!--<logger name="*" minlevel="Trace" writeTo="allfile" />-->
  43. <!--跳过Microsoft开头的相关日志信息-->
  44. <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
  45. <logger name="*" minlevel="Trace" writeTo="database" />
  46. <!--<logger name="*" minlevel="Trace" writeTo="ownFile-web" />-->
  47. </rules>
  48. </nlog>

三、设置Core启用NLog

1、方法一

步骤一:

  1. public class Program
  2. {
  3. public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
  4. WebHost.CreateDefaultBuilder(args)
  5. .UseNLog()//配置NLog(1)
  6. .UseStartup<Startup>();
  7. }

步骤二:

  1. public class Startup
  2. {
  3. public Startup(IConfiguration configuration, IHostingEnvironment env)
  4. {
  5. Configuration = configuration;
  6. //配置NLog(2)
  7. env.ConfigureNLog("nlog.config");
  8. LogManager.Configuration.Variables["connectionString"] = Configuration["ConnectionString:SqlServer:Value"];
  9. LogManager.Configuration.Variables["configDir"] = Configuration.GetSection("LogFilesDir").Value;
  10. }
  11. }

2、方法二

步骤一:

  1. public class Startup
  2. {
  3. public Startup(IConfiguration configuration, IHostingEnvironment env)
  4. {
  5. Configuration = configuration;
  6. //配置NLog(1)
  7. env.ConfigureNLog("nlog.config");
  8. LogManager.Configuration.Variables["connectionString"] = Configuration["ConnectionString:SqlServer:Value"];
  9. LogManager.Configuration.Variables["configDir"] = Configuration.GetSection("LogFilesDir").Value;
  10. }
  11. }

步骤二:

  1. public class Startup
  2. {
  3. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  4. {
  5. if (env.IsDevelopment())
  6. {
  7. app.UseDeveloperExceptionPage();
  8. }
  9. else
  10. {
  11. app.UseExceptionHandler("/Home/Error");
  12. }
  13. //配置NLog(2)
  14. loggerFactory.AddNLog();
  15. app.AddNLogWeb();
  16. }
  17. }

四、记录日志

  1. public IActionResult Index()
  2. {
  3. ViewData["Err"] = string.Empty;
  4. try
  5. {
  6. LogEventInfo ei = new LogEventInfo(NLog.LogLevel.Info, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取PersonalAccount_Apply成功");
  7. ei.Properties["application"] = "myApplication";
  8. Logger logger = LogManager.GetCurrentClassLogger();
  9. logger.Log(ei);
  10. int a = 1 - 1;
  11. int result = 5 / a;
  12. }
  13. catch (Exception ex)
  14. {
  15. LogEventInfo ei = LogEventInfo.Create(NLog.LogLevel.Error, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, ex, null, "获取PersonalAccount_Apply失败");
  16. ei.Properties["application"] = "myApplication";
  17. ei.Properties["callsite"] = "callsite";
  18. Logger logger = LogManager.GetCurrentClassLogger();
  19. logger.Log(ei);
  20. string message = ex.Message;
  21. }
  22. return View();
  23. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/674555
推荐阅读
相关标签
  

闽ICP备14008679号