zoukankan      html  css  js  c++  java
  • 【记录】.net 通用log4net日志配置

    asp.net mvc

    1、引入log4netNuGet包。

    2、修改Global.asax下的Application_Start方法。加入log4net.Config.XmlConfigurator.Configure(),修改如下:

    protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); log4net.Config.XmlConfigurator.Configure(); }

     3、修改web.config文件,增加以下节点配置:

    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
    </configSections>
    <log4net configSource="Configlog4net.config" />

     4、在项目中新建Config文件夹,用于存放配置文件。

     5、在文件夹下新建文件log4net.config,内容如下:

    <?xml version="1.0"?>
    <log4net>
      <root>
        <level value="DEBUG"/>
        <appender-ref ref="SysAppender"/>
        <appender-ref ref="consoleApp"/>
      </root>
      <!--信息日志配置-->
      <appender name="SysAppender" type="log4net.Appender.RollingFileAppender">
        <param name="File" value="Logs\" />
        <param name="AppendToFile" value="true" />
        <param name="MaximumFileSize" value="20MB" />
        <param name="MaxSizeRollBackups" value="100" />
        <param name="StaticLogFileName" value="false" />
        <param name="DatePattern" value="\yyyyMM\yyyyMMdd&quot;.log&quot;" />
        <param name="RollingStyle" value="Composite" />
        <layout type="log4net.Layout.PatternLayout">
          <param name="ConversionPattern" value="%n&#13;&#10;--------------------------------------------------------------------------------------&#13;&#10;%n日志时间:%d [%t] %n日志级别:%-5p %n日 志 类:%c [%x] %n%m %n" />
          <param name="Header" value="&#13;&#10;======================================================================================&#13;&#10;" />
        </layout>
      </appender>
      <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
        <layout type="log4net.Layout.PatternLayout,log4net">
          <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        </layout>
      </appender>
      <logger name="WebLogger">
        <level value="DEBUG"/>
      </logger>
    
    </log4net>

     调用示例:

    private log4net.ILog log = log4net.LogManager.GetLogger("TestJob");
    public void Execute(IJobExecutionContext context)
    {
        var logContent = string.Format("{0}==>>{1}{2}", DateTime.Now, "create new log.", Environment.NewLine);
        log.Info(logContent);
    }

    .net core

    新建Log4netHelper类,内容如下:

    using log4net;
    using log4net.Repository;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Reflection;
    using System.Text;
    
    namespace Five.ScheduleQuartz.Utils.Tool
    {
        /// <summary>
        /// 日志等级
        /// </summary>
        public enum LogLevel
        {
            Error,
            Debug,
            Warning,
            Info
        }
        /// <summary>
        /// 单例模式初始化
        /// </summary>
        public class Singleton
        {
            private ILog Log;
            private static Singleton instance;
            private Singleton() { }
            public static Singleton getInstance()
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
            /// <summary>
            /// 获取日志初始化器
            /// </summary>
            /// <param name="type">类名 方法名</param>
            /// <returns></returns>
            public ILog Init(string type)
            {
                Log = LogManager.GetLogger(Log4netHelper.Repository.Name, type);
                return Log;
            }
        }
        /// <summary>
        /// 日志操作类
        /// </summary>
        public class Log4netHelper
        {
            /// <summary>
            /// log4net 仓储
            /// </summary>
            public static ILoggerRepository Repository { get; set; }
            /// <summary>
            /// 输出Erro日志
            /// </summary>
            /// <param name="message">日志内容</param>
            public static void Error(string message)
            {
                StackTrace trace = new StackTrace();
                //获取是哪个类来调用的  
                var className = trace.GetFrame(1).GetMethod().DeclaringType;
                //获取方法名称
                MethodBase method = trace.GetFrame(1).GetMethod();
                var type = "类名:" + className.Namespace + "
    
    	
    
    方法名:" + method.Name;
                WriteLog(LogLevel.Error, message, type);
            }
            /// <summary>
            /// 输出Warning日志
            /// </summary>
            /// <param name="message">日志内容</param>
            public static void Warning(string message)
            {
                StackTrace trace = new StackTrace();
                //获取是哪个类来调用的  
                var className = trace.GetFrame(1).GetMethod().DeclaringType;
                //获取方法名称
                MethodBase method = trace.GetFrame(1).GetMethod();
                var type = "类名:" + className.Namespace + "
    
    	
    
    方法名:" + method.Name;
                //记录日志
                WriteLog(LogLevel.Warning, message, type);
            }
            /// <summary>
            /// 输出Info日志
            /// </summary>
            /// <param name="message">日志内容</param>
            public static void Info(string message)
            {
                StackTrace trace = new StackTrace();
                //获取是哪个类来调用的  
                var className = trace.GetFrame(1).GetMethod().DeclaringType;
                //获取方法名称
                MethodBase method = trace.GetFrame(1).GetMethod();
                var type = "类名:" + className.Namespace + "
    
    	
    
    方法名:" + method.Name;
                //记录日志
                WriteLog(LogLevel.Info, message, type);
            }
            /// <summary>
            /// 输出Debug日志
            /// </summary>
            /// <param name="message">日志内容</param>
            public static void Debug(string message)
            {
                StackTrace trace = new StackTrace();
                //获取是哪个类来调用的  
                var className = trace.GetFrame(1).GetMethod().DeclaringType;
                //获取方法名称
                MethodBase method = trace.GetFrame(1).GetMethod();
                var type = "类名:" + className.Namespace + "
    
    	
    
    方法名:" + method.Name;
                //记录日志
                WriteLog(LogLevel.Debug, message, type);
            }
            /// <summary>
            /// 写日志
            /// </summary>
            /// <param name="logLevel">日志等级</param>
            /// <param name="message">日志信息</param>
            /// <param name="type">类名 方法名</param>
            private static void WriteLog(LogLevel logLevel, string message, string type)
            {
                ILog Log = Singleton.getInstance().Init(type);
                switch (logLevel)
                {
                    case LogLevel.Debug:
                        Log.Debug(message);
                        break;
                    case LogLevel.Error:
                        Log.Error(message);
                        break;
                    case LogLevel.Info:
                        Log.Info(message);
                        break;
                    case LogLevel.Warning:
                        Log.Warn(message);
                        break;
                }
    
            }
        }
    }
    View Code

     修改Startup如下:

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        //日志配置文件
        Log4netHelper.Repository = LogManager.CreateRepository("NETCoreRepository");
        XmlConfigurator.Configure(Log4netHelper.Repository, new FileInfo("./Config/log4net.config"));
     }

    log4net.config配置文件内容参考上面的内容。

    使用示例:

     Log4netHelper.Info("测试日志内容");
  • 相关阅读:
    Django项目:CRM(客户关系管理系统)--54--45PerfectCRM实现账号快速重置密码
    Django项目:CRM(客户关系管理系统)--53--44PerfectCRM实现账号快速注册登陆
    Python 原生2种 邮件发送(发送验证码) 的方法
    Django项目:CRM(客户关系管理系统)--52--43PerfectCRM实现AJAX全局账号登陆
    Django项目:CRM(客户关系管理系统)--51--42PerfectCRM实现AJAX全局账号注册
    Django项目:CRM(客户关系管理系统)--50--41PerfectCRM实现全局账号密码修改
    Django项目:CRM(客户关系管理系统)--49--40PerfectCRM实现全局账号注册+验证码+页面刷新保留信息
    Django项目:CRM(客户关系管理系统)--48--39PerfectCRM实现登录+验证码+过期时间+页面保留账号
    mvc 伪静态任意扩展名的实现方法
    asp.net mvc各种传值方式大全
  • 原文地址:https://www.cnblogs.com/miskis/p/8119030.html
Copyright © 2011-2022 走看看