zoukankan      html  css  js  c++  java
  • NLog 日志框架搭建讲解(亲测有效,代码齐全)

    前言:最近,搭建代码框架时,想要找一款日志框架。因为之前都是使用Log4net,所以这次打算使用一款新的NLog尝试下,感谢网上的这么多朋友发布的博文,对我有不少的启发作用。不过在对于写日志到数据库这一点,写对的为数不多,所以,我也记录下,算是个学习总结,也希望能帮助其他需要的童鞋。(本文不详细讲解NLog各参数,以及与Log4net的区别,大家可以到网上去搜,很多)

    一、对项目添加NLog

    选择自己想要添加的项目,使用Nuget添加NLog相关插件

    安装好后,项目里会引用 NLog.dll 和 NLog.config,NLog.xsd

    二、对NLog.config进行配置

    NLog.config默认仅给出地址,很少的配置,其余的需要我们自己进行填写

    targets标签:是填写我们所需要的日志级别,里面有 Console,Debugger,File,Database,Mail 等

    rules标签:targets标签要配合rules使用,rules指定了,每个日志所输出的目录地址

    <targets>
        <target name="console" xsi:type ="Console" />
        <target name="debugger" xsi:type="Debugger" layout="${date:format=HH:mm:ss.fff}: ${message}" />
        <target name="error_file" xsi:type="File"
                        fileName="${basedir}/Logs/Error/${shortdate}/error.txt" maxArchiveFiles="30"
                        layout="${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
        <target name="info" xsi:type="File"
                    fileName="${basedir}/Logs/Info/${shortdate}/info.txt" maxArchiveFiles="30"
                    layout="${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
        <target name="database" xsi:type="Database" 
                connectionString ="Data Source=localhost;port=3306;Initial Catalog=Be_Log;user id=root;password=AllenLee;" 
                commandText="INSERT INTO t_user_log(user_id,user_name,action_type,user_ip,add_time,remark) Values(@user_id,@user_name,@action_type,@user_ip,@add_time, @remark);"
                >
          <parameter name = "@user_id" layout = "${event-context:item=user_id}"/>
          <parameter name = "@user_name" layout = "${event-context:item=user_name}" />
          <parameter name = "@action_type" layout = "${event-context:item=action_type}"/>
          <parameter name = "@user_ip" layout = "${event-context:item=user_ip}" />
          <parameter name = "@add_time" layout = "${event-context:item=add_time}" />
          <parameter name = "@remark" layout = "${event-context:item=remark}" />
          <dbProvider>MySql.Data.MySqlClient</dbProvider>
        </target>
        <!-- 发生致命错误发送邮件日志 -->
        <target name="email" xsi:type="Mail"
                   header="-----header------"
                   footer="-----footer-----"
                   layout="${longdate} ${level} ${callsite} ${message} ${exception:format=Message, Type, ShortType, ToString, Method, StackTrace}"
                   html="false"
                   encoding="UTF-8"
                   addNewLines="true"
                   subject="${message}"
                   to=""
                   from=""
                   body="${longdate} ${level} ${callsite} ${message} ${exception:format=Message, Type, ShortType, ToString, Method, StackTrace}"
                   smtpUserName=""
                   enableSsl="false"
                   smtpPassword=""
                   smtpAuthentication="Basic"
                   smtpServer="smtp.163.com"
                   smtpPort="25">
        </target>
    </targets>

    <rules>
    <logger name="*" writeTo="console" />
    <logger name="*" minlevel="Debug" writeTo="debugger" />
    <logger name="*" minlevel="Error" writeTo="error_file" />
    <logger name="*" level="Info" writeTo="info" />
    <logger name="*" writeTo="database" />
    </rules>

    三、日志内容存储

    有了以上配置,我们就可以写一处简单程序来进行测验,看是否能生成日志文件。

    (1)日志文件生成(代码用的是MVC,大家可以随意用其他代码测试)

    通过这几个,可以把日志输入到文件,路径就在我们前面 target 所配置的里面

    打开一个具体文件查看,可见内容和我们程序写的是一样的:

    (2)日志写入数据库(注:此处是MySql,其他请各位自己尝试)

    在MySql中,新建表 t_user_log 结构,与前面 target 中所列的字段相同,将连接字符串等写上。

    注:<dbProvider>MySql.Data.MySqlClient</dbProvider>  这一个千万不要忘了

    然后我们可以使用代码来进行测试:

    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
    LogEventInfo lei = new LogEventInfo();
    lei.Properties["user_id"] = "18";
    lei.Properties["user_name"] = "AllenLee";
    lei.Properties["action_type"] = "Created Log";
    lei.Properties["user_ip"] = "172.16.0.132";
    lei.Properties["add_time"] = DateTime.Now;
    lei.Properties["remark"] = "This is a remark";
    lei.Level = LogLevel.Info;
    Logger.Log(lei);

    执行后,数据库表数据变化:

    可见数据能正常写入到数据库了,至此,无论是写文件,还是写数据库,NLog 都可以实现了。这样在项目里面操作起来就方便多了

    大家如果有什么疑问,欢迎来讨论!

                                           

  • 相关阅读:
    Spring Batch与ETL工具比较
    Spring Batch基本概念
    SpringBatch介绍
    2019第51周日
    用arthas的watch方法观察执行方法的输入输出
    三人行必有我师
    用arthas查看JVM已加载的类及方法信息
    线上问题排查利器Arthas
    换个视觉
    Java Servlet:服务器小程序
  • 原文地址:https://www.cnblogs.com/AllenLee/p/7737863.html
Copyright © 2011-2022 走看看