使用NLog记录日志到数据库

NLog是.NET,NETSTANDARD,Xamarin,Silverlight和Windows Phone的免费日志记录平台,具有丰富的日志路由和管理功能。NLog可以轻松地为您的应用程序生成和管理高品质的日志,而不管其大小或复杂性。

 

下面介绍一下如何使用NLog记录日志到数据库:

1. 打开VS,选择NuGet程序包管理器 -> 管理解决方案的NuGet程序包。

 

2.搜索关键字“NLog”,选择自己的项目,安装“NLog”和“NLog.Config”,项目里会自动生成两个配置文件:NLog.Config 和 NLog.xsd。

 

2.自己建一个记录日志的工具类:DBLog.cs。

 1 using System;
 2 using NLog;
 3 
 4 namespace NLogDemo.Ultity
 5 {
 6 
 7     public class DBLog
 8     {
 9         readonly static Logger processLogger = LogManager.GetLogger("LMDBLog");
10 
11         public static void Process(DateTime createDate, string origin, string logLevel, string message, string stackTrace)
12         {
13             LogEventInfo theEvent = new LogEventInfo(LogLevel.Info, "", message);
14             theEvent.Properties["createDate"] = createDate;
15             theEvent.Properties["origin"] = origin;
16             theEvent.Properties["logLevel"] = logLevel;
17             theEvent.Properties["message"] = message;
18             theEvent.Properties["stackTrace"] = stackTrace;
19             processLogger.Log(theEvent);
20         }
21 
22         public static void Flush()
23         {
24             LogManager.Flush();
25         }
26     }
27 }
DBLog.cs

 

3.Flush();方法在Global.asax中调用,用于在应用程序执行结束后释放资源。

 1 using System;
 2 using System.Web.Mvc;
 3 using System.Web.Routing;
 4 using NLogDemo.Ultity;
 5 
 6 namespace NLogDemo
 7 {
 8     public class MvcApplication : System.Web.HttpApplication
 9     {
10         protected void Application_Start()
11         {
12             AreaRegistration.RegisterAllAreas();
13             RouteConfig.RegisterRoutes(RouteTable.Routes);
14         }
15         protected void Application_End(object sender, EventArgs e)
16         {
17             DBLog.Flush();
18         }
19     }
20 }
Global.asax

 

4.配置NLog.Config,一个<target></target>,一个<rules></rules>。

 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       xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
 5       autoReload="true"
 6       throwExceptions="false"
 7       internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
 8 
 9   <targets>
10     <default-wrapper xsi:type="BufferingWrapper" bufferSize="100" FlushTimeout="10000">
11       <wrapper-target xsi:type="AsyncWrapper"/>
12     </default-wrapper>
13     <target xsi:type="Database" name="LMDBLogTarget">
14       <!-- SQL command to be executed for each entry -->
15       <commandText>
16         INSERT INTO [SystemLogs](createDate, origin,logLevel,message,stackTrace)
17         VALUES(@createDate,@origin,@logLevel,@message,@stackTrace)
18       </commandText>
19       <!-- parameters for the command -->
20       <!--创建日期-->
21       <parameter name="@createDate" layout="${event-properties:item=createDate}" />
22       <!--日记来源-->
23       <parameter name="@origin" layout="${event-properties:item=origin}" />
24       <!--日志级别-->
25       <parameter name="@logLevel" layout="${event-properties:item=logLevel}" />
26       <!--异常信息-->
27       <parameter name="@message" layout=" ${event-properties:item=message}" />
28       <!--堆栈信息-->
29       <parameter name="@stackTrace" layout="${event-properties:item=stackTrace}" />
30 
31       <!-- connection string -->
32       <dbProvider>System.Data.SqlClient</dbProvider>
33       <connectionString>server=192.168.56.53,3000;Initial Catalog=MyLogs;Persist Security Info=True;User ID=yx;Password=yx123;</connectionString>
34     </target>
35   </targets>
36 
37   <rules>
38     <logger name="LMDBLog" minlevel="Trace" writeTo="LMDBLogTarget" final="true"  />
39   </rules>
40 </nlog>
NLog.config

 

5.该配置的都配置好了,接下来就是调用方法记录日志了。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Web.Mvc;
 4 using NLogDemo.Ultity;
 5 
 6 namespace NLogDemo.Controllers
 7 {
 8     public class HomeController : Controller
 9     {
10         // GET: Home
11         public ActionResult Index()
12         {
13             List<int> intList = new List<int>();
14             try
15             {
16                 DBLog.Process(DateTime.Now, "Home/Index", Enum.GetName(typeof(LogType),3), "Home/Index" + "开始执行" , "");
17 
18                 //制造异常
19                 intList.Add(Convert.ToInt32(""));
20 
21                 return View(intList);
22             }
23             catch (Exception ex)
24             {
25                 DBLog.Process(DateTime.Now, "Home/Index", Enum.GetName(typeof(LogType), 4), ex.Message, ex.StackTrace);
26                 return null;
27             }
28         }
29     }
30 }
HomeController.cs
using System.ComponentModel;

namespace NLogDemo
{
    public enum LogType
    {
        [Description("错误")]
        错误 = 1,

        [Description("警告")]
        警告 = 2,

        [Description("记录")]
        记录 = 3,

        [Description("异常")]
        异常 = 4,
    }
}
LogType.cs

 

6.查询数据库中记录的日志数据。

 

7.另附数据库建表的脚本。

CREATE TABLE [dbo].[SystemLogs](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [createDate] [datetime] NOT NULL,
    [origin] [varchar](50) NOT NULL,
    [logLevel] [varchar](50) NOT NULL,
    [message] [varchar](500) NOT NULL,
    [stackTrace] [varchar](500) NOT NULL
 CONSTRAINT [PK_SystemLogs] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

 

自己亲测有效,有问题可留言讨论哈【笔芯】

/*****************************我是可爱的分割线*******************************/

 

posted @ 2017-08-21 11:15  Merryan  阅读(1011)  评论(0)    收藏  举报