zoukankan      html  css  js  c++  java
  • log4net 写日志配置

    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 ="LogTrace-"/>
          <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("
    .客户信息:");
                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("
    	Ip:" + ip);
                str.Append("
    	浏览器:" + Request.Browser.Browser.ToString());
                str.Append("
    	浏览器版本:" + Request.Browser.MajorVersion.ToString());
                str.Append("
    	操作系统:" + Request.Browser.Platform.ToString());
                str.Append("
    .错误信息:");
                str.Append("
    	页面:" + Request.Url.ToString());
                str.Append("
    	错误信息:" + ex.Message);
                str.Append("
    	错误源:" + ex.Source);
                str.Append("
    	异常方法:" + ex.TargetSite);
                str.Append("
    	堆栈信息:" + ex.StackTrace);
                str.Append("
    --------------------------------------------------------------------------------------------------");
                //创建路径 
                LogWriter.Default.WriteError(str.ToString());
            }

    5、项目 AssemblyInfo.cs 文件加入

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

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

  • 相关阅读:
    vue axios接口封装、Promise封装、简单的axios方法封装、vue接口方法封装、vue post、get、patch、put方法封装
    vue-router 报错、:Avoided redundant navigation to current location 错误、路由重复
    微信小程序支付、小程序支付功能、小程序支付方法、微信小程序支付方法
    微信小程序热更新,小程序提示版本更新,版本迭代,强制更新,微信小程序版本迭代
    微信小程序动态修改title,动态配置title,动态配置头部,微信小程序动态配置头部
    响应式布局rem、rem方法封装、移动端响应式布局
    jquery 选项卡切换、选项卡封装、简单的jquery选项卡封装、tab切换效果
    js获取url并截取相应的字段,js解决url获取中文字段乱码问题
    微信小程序接口封装、原生接口封装、request、promise封装
    20193327《Python程序设计》实验报告三
  • 原文地址:https://www.cnblogs.com/echosong/p/4876952.html
Copyright © 2011-2022 走看看