转:使用Nlog记录日志到数据库
原文:http://www.cnblogs.com/Gyoung/archive/2012/10/18/2729613.html
Nlog是一个很不错的.NET日志记录组件,它可以将日志输出到控件台,保存到文本,也可以很方便的记录到数据库中。
可以在这里下载Nlog:http://nlog-project.org/
这里分享一下如何配置Nlog,可以使其日志记录到数据库中(这里我用的是SQL server 2008).
新建一个控件台项目:NlogSample,再通过NuGet加入Nlog程序集,如果没有装NuGet也可以在Nlog官网上下载,如图:

安装好以后,在项目中就有了Nlog程序集和Nlog.config文件
打开Nlog.config文件,在target节点中,增加对数据库的配置。

<target type="Database" name="database" connectionstring="Data Source=.;Initial Catalog=ReportServerTempDB;Integrated Security=True">
<commandText>
insert into MyLog ([CreateDate], [Origin], [LogLevel], [Message], [StackTrace]) values (@createDate, @origin, @logLevel, @message, @stackTrace);
</commandText>
<parameter name="@createDate" layout="${longdate}"/>
<!--日志发生时间-->
<parameter name="@origin" layout="${callsite}"/>
<!--日志来源-->
<parameter name="@logLevel" layout="${level}"/>
<!--日志等级-->
<parameter name="@message" layout="${message}"/>
<!--日志信息-->
<parameter name="@stackTrace" layout="${stacktrace}"/>
<!--堆栈信息-->
</target>

其中:connectionstring是数据库连接串,commandText是插入的SQL语句,parameter 是参数信息。当然在记录之前我们要先在数据库中建好相应的表。
在Nlog.config中的rule中增加日志记录规则

<rules>
<!-- add your logging rules here -->
<logger name="*" writeTo="database"/>
<!--
<logger name="*" minlevel="Trace" writeTo="f" />
-->
</rules>

这样,我们的Nlog.config就设置好了。在Main方法中写几句代码测试一下:

class Program
{
private static Logger logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
logger.Fatal("发生致命错误");
}
}

执行成功,数据库中已经增加一条日志记录了
LigID CreateDate Origin LogLevel Message Exception StackTrace
20 2012-10-18 15:49:16.4114 NlogSample.Program.Main Fatal 发生致命错误 NULL AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main
我们也可以将日志等级比较低的记录到文本,只将比较严重的日志记录到数据库中,相应的Nlog.config如下:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug"> <!--
See http://nlog-project.org/wiki/Configuration_file
for information on customizing logging rules and outputs.
-->
<!--<nlog throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug" />-->
<targets>
<!-- add your targets here -->
<target name="file" xsi:type="File" fileName="${basedir}/logs/Log ${shortdate}.txt" layout="${longdate} ${callsite} ${level}: ${message} ${event-context:item=exception} ${stacktrace}" />
<target type="Database" name="database" connectionstring="Data Source=.;Initial Catalog=ReportServerTempDB;Integrated Security=True">
<commandText>
insert into MyLog ([CreateDate], [Origin], [LogLevel], [Message], [StackTrace]) values (@createDate, @origin, @logLevel, @message, @stackTrace);
</commandText>
<parameter name="@createDate" layout="${longdate}"/><!--日志发生时间-->
<parameter name="@origin" layout="${callsite}"/><!--日志发生时间-->
<parameter name="@logLevel" layout="${level}"/><!--日志等级-->
<parameter name="@message" layout="${message}"/><!--日志信息-->
<parameter name="@stackTrace" layout="${stacktrace}"/><!--日志发生时间-->
</target>
<!--
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
</targets> <rules>
<!-- add your logging rules here -->
<logger name="*" writeTo="file"/>
<logger name="*" minlevel="Error" appendTo="database"/>
<!--
<logger name="*" minlevel="Trace" writeTo="f" />
-->
</rules>
</nlog>

在根结点上设置:throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug" ,可以让我们看到Nlog的内部错误,对调试有很大的帮助。
这里也许有人要问,上面日志表中的参数${longdate},${level} 等都是Nlog内部恰好有提供的,要是我要记录的信息Nlog没有怎么办?没问题,我们完全可以自己定义日志
表的数据结构。
重新配置Nlog.Config如下:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
throwExceptions="true" internalLogFile="c:\nlog1.txt" internalLogLevel="Debug"> <!--
See http://nlog-project.org/wiki/Configuration_file
for information on customizing logging rules and outputs.
-->
<targets>
<!-- add your targets here -->
<target name="file" xsi:type="File" fileName="D:\ProcLogs/${event-context:item=appName}/${event-context:item=moduleName}/${event-context:item=procName}/${event-context:item=logTitle}/${shortdate}-${level}.txt"
layout="${longdate} ${level}:${event-context:item=logMessage}" />
<target name="fi" xsi:type="File" fileName="${basedir}/logs/Log ${shortdate}.txt"
layout="${longdate} ${level}:${message} ${stacktrace}" />
<target type="Database" name="database" connectionstring="Data Source=.;Initial Catalog=ReportServerTempDB;Integrated Security=True">
<commandText>
insert into DevLog ([AppName],[ModuleName],[ProcName],[LogLevel],[LogTitle],[LogMessage],[LogDate],[StackTrace]) values (@appName, @moduleName, @procName, @logLevel, @logTitle, @logMessage,@logDate,@stackTrace);
</commandText>
<parameter name="@appName" layout="${event-context:item=appName}"/>
<parameter name="@moduleName" layout="${event-context:item=moduleName}"/>
<parameter name="@procName" layout="${event-context:item=procName}"/>
<parameter name="@logLevel" layout="${event-context:item=logLevel}"/>
<parameter name="@logTitle" layout="${event-context:item=logTitle}"/>
<parameter name="@logMessage" layout="${event-context:item=logMessage}"/>
<parameter name="@logDate" layout="${longdate}"/>
<parameter name="@stackTrace" layout="${stacktrace}"/>
</target>
<!--
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
</targets> <rules>
<!-- add your logging rules here -->
<logger name="Log" writeTo="file"/>
<logger name="L" writeTo="fi"/>
<!--<logger name="Log" minlevel="Info" appendTo="database"/>-->
<!--
<logger name="*" minlevel="Trace" writeTo="f" />
-->
</rules>
</nlog>

类似<parameter name="@appName" layout="${event-context:item=appName}"/> ,我们就可以定义自己的参数。
然后在写日志的时候,可以通过LogEventInfo 类给我们的参数赋值,代码如下:

void WriteLog(LogLevel levle, string appName, string moduleName, string procName, string logLevel, string logTitle, string logMessage)
{
LogEventInfo ei = new LogEventInfo(levle, "", "");
ei.Properties["appName"] = appName;
ei.Properties["moduleName"] = moduleName;
ei.Properties["procName"] = procName;
ei.Properties["logLevel"] = logLevel.ToUpper();
ei.Properties["logTitle"] = logTitle;
ei.Properties["logMessage"] = logMessage;
logger.Log(ei);
}

示例项目下载:点我
注意,设置数据库时,时间要为字符串类型。
深入的文章 http://www.cnblogs.com/dflying/category/78087.html 很不错,大家可以去看看
转:使用Nlog记录日志到数据库的更多相关文章
- [转]C# 使用Nlog记录日志到数据库
本文转自:http://www.cnblogs.com/weixing/archive/2013/04/26/3044422.html 摘要]Nlog是一个很不错的.NET日志记录组件,它可以将日志输 ...
- C# 使用Nlog记录日志到数据库 使用LogEventInfo类获取,命名空间名称、类名、方法名
原文地址:http://dotnet.9sssd.com/csbase/art/793 [摘要]Nlog是一个很不错的.NET日志记录组件,它可以将日志输出到控件台,保存到文本,也可以很方便的记录到数 ...
- C# 使用Nlog记录日志到数据库
[摘要]Nlog是一个很不错的.NET日志记录组件,它可以将日志输出到控件台,保存到文本,也可以很方便的记录到数据库中.本文为你介绍C# 使用Nlog记录日志到数据库. Nlog是一个很不错的.NET ...
- 使用Nlog记录日志到数据库
Nlog是一个很不错的.NET日志记录组件,它可以将日志输出到控件台,保存到文本,也可以很方便的记录到数据库中. 可以在这里下载Nlog:http://nlog-project.org/ 这里分享一下 ...
- 从零开始搭建前后端分离的NetCore2.2(EF Core CodeFirst+Autofac)+Vue的项目框架之四Nlog记录日志至数据库
为什么要进行日志记录呢?为什么要存至数据库呢?只能说日志记录是每个系统都应当有的. 好的日志记录方式可以提供我们足够多定位问题的依据.查找系统或软件或项目的错误或异常记录.程序在运行时就像一个机器人, ...
- .Net Core 使用NLog记录日志到文件和数据库
NLog 记录日志是微软官方推荐使用. 接下来,通过配置日志记录到文件和Sql Server数据库. 第一步:首先添加包NLog.Config (可通过微软添加包命令Install-Package 包 ...
- EF+LINQ事物处理 C# 使用NLog记录日志入门操作 ASP.NET MVC多语言 仿微软网站效果(转) 详解C#特性和反射(一) c# API接受图片文件以Base64格式上传图片 .NET读取json数据并绑定到对象
EF+LINQ事物处理 在使用EF的情况下,怎么进行事务的处理,来减少数据操作时的失误,比如重复插入数据等等这些问题,这都是经常会遇到的一些问题 但是如果是我有多个站点,然后存在同类型的角色去操作 ...
- Asp.Net Core中使用NLog记录日志
2019/10/28, Asp.Net Core 3.0, NLog 4.6.7, NLog.Web.AspNetCore 4.9.0 摘要:NLog在asp.net网站中的使用,NLog日志写入数据 ...
- .NET中使用NLog记录日志
以前小编记录日志使用的是Log4Net,虽然好用但和NLog比起来稍显复杂.下面小编就和大伙分享一下NLog的使用方式. 引用NLog.Config 在使用NLog之前,我们要首先添加对NLog.Co ...
随机推荐
- node.js 的 os 模块
Node.js的os module 提供了一系列跟操作系统相关的操作函数,比较简单,所以功能也就十分有限.我们可以去官网看各个函数的介绍: http://nodejs.org/api/os.html ...
- 配置<authorization>节(配置文件)
在 Web.config 文件的<configuration>标记的子标记<authorization>和</authorization>之间用于设置应用程序的授权 ...
- Qt4.8.6 Embedded Linux 的编译与移植
最近买了个飞凌ok6410 的开发板,于是在其中搭建qt4.8.6运行环境.费了两三天时间,主要还是对Linux系统的生疏,在一些问题上徘徊很久,在这里做一些过程笔记.烧写ARM-Linux系统,根据 ...
- codeforce A. Design Tutorial: Learn from Math
题意:将一个数拆成两个合数的和, 输出这两个数!(这道题做的真是TMD水啊)开始的时候不知道composite numbers是啥意思,看了3遍才看懂.... 看懂之后又想用素数筛选法来做,后来决定单 ...
- 从零开始Grunt
[20141025]从0开始Grunt *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom ...
- ActionLink()与jquery更好地结合建造MVC网页:
众所周知,微软的MVC框架提供了一系列Helper以用于创建Ajax的网页. 但是,类似于Ajax.ActionLink()的方法创建的Ajax缺乏足够的灵活性,例如: 页面上有很多选项,我们需要根据 ...
- 环信SDK与Apple Watch的结合(1)
该系列是记录在apple watch上开发IM,用到了最近挺流行的环信IM SDK. 一.先来一段网上随处可查到的信息: 1.两种分辨率 1.65寸 312*390 1.5寸 272*340 2.开发 ...
- Windows Azure开发者任务之五:配置虚拟机的“规模”
指定虚拟机的“规模”是怎么一回事? 我们可以指定角色将要部署于其上的虚拟机的“规模”.虚拟机的“规模”是指: 1,CPU核心数 2,内存容量 3,本地文件系统的体积 我们可以针对具体的角色来指定虚拟机 ...
- SQL Server密码管理的六个危险判断
当管理SQL Server内在的帐户和密码时,我们很容易认为这一切都相当的安全.但实际上并非如此.在这里,我们列出了一些对于SQL Server密码来说非常危险的判断. 当管理SQL Server内在 ...
- Studio for WPF:使用 C1TileView 创建图片库
C1TileView 提供了数据交互浏览的功能.允许我们设置最大化和最小化浏览模板,我们可以通过最小化模板快速定位详细浏览选项. 下面我们分步分享实现方法: 1.添加 C1TileView 到窗体,并 ...