当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET MVC 使用 Log4net 记录日志

ASP.NET MVC 使用 Log4net 记录日志

2018年08月21日  | 移动技术网IT编程  | 我要评论

不疯魔不成活txt,死侍迅雷下载电影天堂,酒泉市人事人才网

log4net 介绍

log4net 是 apache 下一个开放源码的项目,它是log4j 的一个克隆版。我们可以控制日志信息的输出目的地。log4net中定义了多种日志信息输出模式。它可以根据需要将日志输出到控制台,文本文件,windows 日志事件查看器中,包括数据库,邮件等等位置,以便我们快速跟踪程序bug。

log4net 提供 7个日志等级,从高到底分别为:off > fatal > error > warn > info > debug  > all

log4net 有 3个主要的成员, loggers ,appenders 和 layouts 。 

  • logger 介绍
    logger是负责日志的记录者,假设我们需要记录一些正常的运行时日志和出现异常时的错误日志,那么我们可以通过在配置文件当中添加两个logger实现。logger主要用于记录日志的分类和控制日志的级别。它可以以多种格式输出日志信息,同时它也可以控制日志的输出级别。
    log4net使用继承体系,也就是说假如存在两个logger,名字分别为a.b.c和a.b。那么a.b就是a.b.c的祖先。每个logger都继承了它祖先的属性
  • appender 介绍
    提供日志记录的输出源,我们可以将日志输出到控制台,文本文件, windows 日志事件查看器中( 在window日志>应用程序 中查看),数据库,邮件等。这些输出源都是通过 appender 来配置实现。
    不建议将日志文件保存到数据库中,因为使用 sql 去排查日志还是比较困难的,最好是将日志文件保存的日志管理服务或elasticsearch,该服务可以提供良好的全文索引以及其他功能。
  • layout 介绍
    layout 用于控制 appender 的输出格式。
    layout 中 patternlayout 约定的字符串转换解释
        %m、%message         输出的日志消息
        %d、%datetime        输出当前语句运行的时刻,格式%date{yyyy-mm-dd hh:mm:ss,fff}
        %r、%timestamp       输出程序从运行到执行到当前语句时消耗的毫秒数
        %p、%level           日志的当前优先级别
        %c、%logger          当前日志对象的名称
        %l、%line            输出语句所在的行号
        %f、%file            输出语句所在的文件名,警告:只在调试的时候有效,调用本地信息会影响性能
        %a、%appdomain       引发日志事件的应用程序域的名称。
        %c、%class、%type    引发日志请求的类的全名,警告:会影响性能
        %exception           异常信息
        %u、%identity        当前活动用户的名字,我测试的时候%identity返回都是空的。警告:会影响性能
        %l、%location        引发日志事件的名空间、类名、方法、行号。警告:会影响性能,依赖pdb文件
        %m、%method          发生日志请求的方法名,警告:会影响性能
        %n、%newline         换行符
        %x、%ndc             ndc(nested diagnostic context)
        %x、%mdc、%p、%properties  等介于 %property
        %property           输出{log4net:identity=, log4net:username=, log4net:hostname=} 
        %t、%thread         引发日志事件的线程,如果没有线程名就使用线程号。
        %w、%username       当前用户的windowsidentity,类似:hostname/username。警告:会影响性能
        %utcdate            发生日志事件的utc时间。例如:%utcdate{hh:mm:ss,fff}
        %%                  输出一个百分号

    更多内容请参考:http://logging.apache.org/log4net/release/sdk/html/t_log4net_layout_patternlayout.htm

如何使用

以 asp.net mvc 项目为例

 1.使用 nuget 安装 log4net ,

pm> install-package log4net

2.创建 log4net.config 配置文件 ,并且将该文件的属性“复制到输出目录”修改为 “始终复制”

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configsections>
    <section name="log4net" type="log4net.config.log4netconfigurationsectionhandler,log4net-net-2.0"/>
  </configsections>
  <log4net>
    <root>
      <level value="all" />
      <appender-ref ref="logfileappender" />
      <!--<appender-ref ref="eventlogappender" />-->
    </root>
    <!--定义输出到文件-->
    <appender name ="logfileappender" type="log4net.appender.rollingfileappender">
      <!--定义文件存放位置-->
      <param name="file" value ="app_data\"/>
      <param name="appendtofile" value="true" />
      <param name="maxsizerollbackups" value="100" />
      <param name="maxfilesize" value="10240" />
      <param name="staticlogfilename" value="false" />
      <!--文件名格式-->
      <param name="datepattern" value="yyyy.mm.dd'.txt'" />
      <param name="rollingstyle" value ="date" />
      <!--不以独占方式记录日志,仅在记录每个日志的最短时间内锁定,因为部署到服务器上遇到了文件被占用无法下载日志-->
      <lockingmodel type="log4net.appender.fileappender+minimallock" />
      <layout type="log4net.layout.patternlayout">
        <!--定义输出格式-->
        <!--示例 2018-08-20 12:10:49,348 -线程id:[21] 日志级别:[info ] : [日志信息]-->
        <param name="conversionpattern" value="%date 线程id:[%thread] 日志级别:[%-5level] : [%message]%newline"/>
      </layout>
      <!--过滤级别 fatal > error > warn > info > debug-->
      <filter type="log4net.filter.levelrangefilter">
        <param name="levelmin" value="debug" />
        <param name="levelmax" value="fatal" />
      </filter>
    </appender>
    <!--定义输出到 windows 事件中-->
    <appender name="eventlogappender" type="log4net.appender.eventlogappender">
      <layout type="log4net.layout.patternlayout">
        <conversionpattern value="%date [%thread] %-5level %logger [%property{ndc}] - %message%newline"></conversionpattern>
      </layout>
    </appender>
  </log4net>
</configuration>

3.创建 loghelper 类,提供日志记录的方法

public class loghelper
    {
        private ilog _log4net = null;
        private const string default_logger_name = "logger";
        /// <summary>
        /// prevents a default instance of the <see cref="logwriter"/> class from being created.
        /// </summary>
        /// <param name="log4netinstance">the log4net instance to be used.</param>
        private loghelper(ilog log4netinstance)
        {
            _log4net = log4netinstance;
        }

        /// <summary>
        /// gets a logger with the specified configuration name.
        /// </summary>
        /// <param name="configname">name of the logger in the configuration.</param>
        /// <returns>the logger obtained.</returns>
        /// <exception cref="system.configuration.configurationexception">thrown when no logger with the specified configuration name was found.</exception>
        public static loghelper getlogger(string configname)
        {
            var logger = logmanager.getlogger(configname);
            if (logger == null)
            {
                throw new argumentexception(string.format("no logger configuration named '{0}' was found in the configuration.", configname), "configname");
            }
            return new loghelper(logger);
        }

        /// <summary>
        /// gets the default.
        /// </summary>
        public static loghelper default
        {
            get
            {
                return getlogger(default_logger_name);
            }
        }

        /// <summary>
        /// writes an information level logging message.
        /// </summary>
        /// <param name="message">the message to be written.</param>
        public void writeinfo(object message)
        {
            _log4net.info(message);
        }

        /// <summary>
        /// writes a warning level logging message.
        /// </summary>
        /// <param name="message">the message to be written.</param>
        public void writewarning(object message)
        {
            _log4net.warn(message);
        }

        /// <summary>
        /// writes a warning level logging message.
        /// </summary>
        /// <param name="message">the message to be written.</param>
        /// <param name="exception">the exception.</param>
        public void writewarning(object message, system.exception exception)
        {
            _log4net.warn(message, exception);
        }

        /// <summary>
        /// writes the error.
        /// </summary>
        /// <param name="message">the message to be written.</param>
        public void writeerror(object message)
        {
            _log4net.error(message);
        }

        /// <summary>
        /// writes the error level logging message..
        /// </summary>
        /// <param name="message">the message to be written.</param>
        /// <param name="exception">the exception.</param>
        public void writeerror(object message, system.exception exception)
        {
            _log4net.error(message, exception);
        }

        /// <summary>
        /// writes the fatal error level logging message..
        /// </summary>
        /// <param name="message">the message to be written.</param>
        public void writefatal(object message)
        {
            _log4net.fatal(message);
        }

        /// <summary>
        /// writes the fatal error level logging message..
        /// </summary>
        /// <param name="message">the message to be written.</param>
        /// <param name="exception">the exception.</param>
        public void writefatal(object message, system.exception exception)
        {
            _log4net.fatal(message, exception);
        }

        public void deletelog()
        {
            string logdirpath = path.combine(path.getdirectoryname(system.reflection.assembly.getexecutingassembly().location), "log");
            if (!directory.exists(logdirpath)) return;
            int days = 30;
            foreach (string filepath in directory.getfiles(logdirpath))
            {
                datetime dt;
                datetime.tryparse(path.getfilenamewithoutextension(filepath).replace(@"log\", "").replace(".", "-"), out dt);
                if (dt.adddays(days).compareto(datetime.now) < 0)
                {
                    file.delete(filepath);
                }
            }
        }
    }
view code

 

4. 在 global.asax 文件 application_start 方法中加载你的 log4net.config 文件,并调用 loghelper类测试记录日志。

log4net.config.xmlconfigurator.configure(new fileinfo(server.mappath("~/log4net.config")));
loghelper.default.writeinfo("appstart"); loghelper.default.writewarning("warning"); loghelper.default.writeerror("error"); loghelper.default.writefatal("fatal"); try { int a = 3 / 4; int r = 4 / a; } catch (exception ex) { loghelper.default.writeerror(ex.message, ex); }

5. 日志效果图

 

可能遇到的问题

由于 log4net 默认是独占文件的,如果程序部署在ftp空间上又需要下载日志文件的时候,会发现无法下载(进程被占用),此时需要更改 appender(输出源) 的 lockingmodel 。

更多lockingmodel 信息,请参考 https://logging.apache.org/log4net/release/sdk/html/p_log4net_appender_fileappender_lockingmodel.htm

<!--不以独占方式记录日志,仅在记录每个日志的最短时间内锁定,因为部署到服务器上遇到了文件被占用无法下载日志-->
<lockingmodel type="log4net.appender.fileappender+minimallock" />

示例下载

 

参考

https://logging.apache.org/log4net/release/manual/introduction.html

https://github.com/apache/logging-log4net/

https://stackify.com/log4net-guide-dotnet-logging/?utm_referrer=https://www.google.com/

http://www.cnblogs.com/lizhiw/p/4317198.html?utm_source=tuicool&utm_medium=referral

http://lovecjh.com/2018/06/08/log4net%e4%bd%bf%e7%94%a8/

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网