码迷,mamicode.com
首页 > Web开发 > 详细

log4net 写日志配置

时间:2015-10-14 12:12:26      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:

1、

nuget install package log4net

2、站点跟目录新建配置文件 LogWriterConfig.xml

<?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" />
    </root>

    <logger name="Idc.Logger" additivity="false">
      <appender-ref ref="LogFileAppender" />
    </logger>

    <!--Log File Setting-->
    <appender name ="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value ="Log\Trace-"/>
      <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‘.log‘" />
      <param name="RollingStyle" value ="Date" />

      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss,fff} %-5p : %m%n"/>
      </layout>

      <!--FATAL > ERROR > WARN > INFO > DEBUG-->
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="WARN" />
        <param name="LevelMax" value="FATAL" />
      </filter>
    </appender>
  </log4net>
</configuration>

3、新建类

  public class LogWriter
    {
        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 LogWriter(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 LogWriter 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 LogWriter(logger);
        }

        /// <summary>
        /// Gets the default.
        /// </summary>
        public static LogWriter 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);
                }
            }
        }
    }

4、在Global.asax 文件cs 里面加入代码

 protected void Application_Start () {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            WeixinConfig.Register();
            log4net.Config.XmlConfigurator.Configure(new FileInfo("LogWriterConfig.xml"));
            LogWriter.Default.WriteWarning("app started.");
        }


        protected void Application_End () {
            LogWriter.Default.WriteWarning("app stopped.");
        }
        protected void Application_Error (object sender, EventArgs e) {
            Exception ex = Server.GetLastError().GetBaseException();
            StringBuilder str = new StringBuilder();
            str.Append("\r\n.客户信息:");
            string ip = "";
            if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null) {
                ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
            } else {
                ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
            }
            str.Append("\r\n\tIp:" + ip);
            str.Append("\r\n\t浏览器:" + Request.Browser.Browser.ToString());
            str.Append("\r\n\t浏览器版本:" + Request.Browser.MajorVersion.ToString());
            str.Append("\r\n\t操作系统:" + Request.Browser.Platform.ToString());
            str.Append("\r\n.错误信息:");
            str.Append("\r\n\t页面:" + Request.Url.ToString());
            str.Append("\r\n\t错误信息:" + ex.Message);
            str.Append("\r\n\t错误源:" + ex.Source);
            str.Append("\r\n\t异常方法:" + ex.TargetSite);
            str.Append("\r\n\t堆栈信息:" + ex.StackTrace);
            str.Append("\r\n--------------------------------------------------------------------------------------------------");
            //创建路径 
            LogWriter.Default.WriteError(str.ToString());
        }

5、项目 AssemblyInfo.cs 文件加入

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "LogWriterConfig.xml", Watch = true)]

6、大功告成可以在开发使用了

 

log4net 写日志配置

标签:

原文地址:http://www.cnblogs.com/echosong/p/4876952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!