C# log4net 的日志代码配置

 

代码配置编写

1、引用dll

2、代码编写配置 

3、生成的目录

 

 /// <summary>
    /// 日志记录TXT
    /// </summary>
    public class LogHelper
    {
        public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("Info");
        public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("Error");
        public static bool app = false;
        public LogHelper()
        {
        }
        /// <summary>
        /// 配置
        /// </summary>
        private static void Run()
        {
            try
            {
                if (app)
                {
                    return;
                }
                app = true;
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null));
                XmlElement configuration = xmlDoc.CreateElement("configuration");
                XmlElement root = xmlDoc.CreateElement("log4net");
                string[] leves = new string[] { "Info", "Error" };
                foreach (string myleve in leves)
                {
                    XmlElement appender = xmlDoc.CreateElement("appender");
                    appender.SetAttribute("name", "Tast" + myleve);
                    appender.SetAttribute("type", "log4net.Appender.RollingFileAppender");
                    XmlElement param = xmlDoc.CreateElement("param");
                    param.SetAttribute("name", "Encoding");
                    param.SetAttribute("value", "utf-8");
                    appender.AppendChild(param);
                    XmlElement file = xmlDoc.CreateElement("file");
                    file.SetAttribute("value", "Log\\" + myleve + "\\");
                    appender.AppendChild(file);
                    XmlElement appendToFile = xmlDoc.CreateElement("appendToFile");
                    appendToFile.SetAttribute("value", "true");
                    appender.AppendChild(appendToFile);

                    XmlElement rollingStyle = xmlDoc.CreateElement("rollingStyle");
                    rollingStyle.SetAttribute("value", "Composite");
                    appender.AppendChild(rollingStyle);

                    XmlElement maxSizeRollBackups = xmlDoc.CreateElement("maxSizeRollBackups");
                    maxSizeRollBackups.SetAttribute("value", "-1");
                    appender.AppendChild(maxSizeRollBackups);

                    XmlElement maximumFileSize = xmlDoc.CreateElement("maximumFileSize");
                    maximumFileSize.SetAttribute("value", "10240MB");
                    appender.AppendChild(maximumFileSize);

                    XmlElement lockingModel = xmlDoc.CreateElement("lockingModel");
                    lockingModel.SetAttribute("type", "log4net.Appender.FileAppender+MinimalLock");
                    appender.AppendChild(lockingModel);

                    XmlElement staticLogFileName = xmlDoc.CreateElement("staticLogFileName");
                    staticLogFileName.SetAttribute("value", "false");
                    appender.AppendChild(staticLogFileName);

                    XmlElement DatePattern = xmlDoc.CreateElement("DatePattern");
                    DatePattern.SetAttribute("value", "yyyy-MM-dd'.txt'");
                    appender.AppendChild(DatePattern);

                    XmlElement layout = xmlDoc.CreateElement("layout");
                    layout.SetAttribute("type", "log4net.Layout.PatternLayout");

                    XmlElement conversionPattern = xmlDoc.CreateElement("conversionPattern");
                    switch (myleve)
                    {
                        case "Error":
                            conversionPattern.SetAttribute("value", @"%n==========%n【日志级别】%-5level %n【记录时间】%date %n【线程编号】[%thread] %n【执行时间】[%r]毫秒 %n【出错文件】%F %n【出错行号】%L %n【出错的类】%logger 属性[%property{NDC}] %n【错误描述】%message %n【错误详情】%newline");
                            break;
                        case "Info":
                            conversionPattern.SetAttribute("value", @"%n========== %n【记录时间】%date %n【记录的类】%logger 属性[%property{NDC}] %n【内容描述】%message %newline");
                            break;

                        default:
                            break;
                    }

                    layout.AppendChild(conversionPattern);
                    appender.AppendChild(layout);

                    XmlElement logger = xmlDoc.CreateElement("logger");
                    logger.SetAttribute("name", myleve);
                    XmlElement level = xmlDoc.CreateElement("level");
                    level.SetAttribute("value", "ALL");
                    XmlElement appender_ref = xmlDoc.CreateElement("appender-ref");
                    appender_ref.SetAttribute("ref", "Tast" + myleve);
                    logger.AppendChild(level);
                    logger.AppendChild(appender_ref);
                    root.AppendChild(appender);
                    root.AppendChild(logger);
                }
                configuration.AppendChild(root);
                xmlDoc.AppendChild(configuration);
                byte[] array = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);
                MemoryStream stream = new MemoryStream(array);
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                log4net.Config.XmlConfigurator.Configure(reader.BaseStream);
            }
            catch (Exception)
            {
            }

        }
        /// <summary>
        /// 信息日志
        /// </summary>
        /// <param name="info"></param>
        public static void WriteLog(string message, string info = "")
        {

            Run();
            if (loginfo.IsInfoEnabled)
            {
                StackTrace trace = new StackTrace();
                MethodBase methodName = trace.GetFrame(1).GetMethod();
                loginfo.Info(methodName.ReflectedType.FullName + "=>" + methodName.Name + "=>" + info + message);
            }
        }
        /// <summary>
        /// 信息日志,对象转json
        /// </summary>
        /// <param name="info"></param>
        public static void WriteLogJson(object message, string info = "")
        {
            Run();
            if (loginfo.IsInfoEnabled)
            {
                StackTrace trace = new StackTrace();
                MethodBase methodName = trace.GetFrame(1).GetMethod();
                loginfo.Info(methodName.ReflectedType.FullName + "=>" + methodName.Name + "=>" + info + message.ObjectToJson());
            }
        }
        /// <summary>
        /// 异常日志
        /// </summary> 
        /// <param name="ex"></param>
        public static void WriteError(Exception ex, object message = null, string info = "")
        {
            Run();
            if (logerror.IsErrorEnabled)
            {
                StackTrace trace = new StackTrace();
                MethodBase methodName = trace.GetFrame(1).GetMethod();
                if (message == null)
                {
                    logerror.Error(methodName.ReflectedType.FullName + "=>" + methodName.Name + "=>" + info + ex.Message, ex);

                }
                else
                {
                    logerror.Error(methodName.ReflectedType.FullName + "=>" + methodName.Name + "=>" + info + message, ex);

                }
            }
        }
        /// <summary>
        /// 异常日志,对象转json
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="message"></param>
        public static void WriteErrorJson(Exception ex, object message = null, string info = "")
        {
            Run();
            if (logerror.IsErrorEnabled)
            {
                StackTrace trace = new StackTrace();
                MethodBase methodName = trace.GetFrame(1).GetMethod();
                if (message == null)
                {
                    logerror.Error(methodName.ReflectedType.FullName + "=>" + methodName.Name + "=>" + info + ex.Message, ex);
                }
                else
                {

                    logerror.Error(methodName.ReflectedType.FullName + "=>" + methodName.Name + "=>" + info + message.ObjectToJson(), ex);

                }
            }
        }
    }

 

posted @ 2019-08-29 11:06  怪先生  阅读(620)  评论(0编辑  收藏  举报