首页 > 编程语言 >C#log4net用法

C#log4net用法

时间:2023-08-24 22:48:32浏览次数:36  
标签:log4net string format C# void args 用法 LogLevel public

新建一个名为log4net.config的文件,然后把下面一段粘贴进去

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<log4net>
		<!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
		<!-- Set root logger level to ERROR and its appenders -->
		<root>
			<level value="ALL"/>
			<appender-ref ref="SysAppender"/>
		</root>
		<!-- Print only messages of level DEBUG or above in the packages -->
		<logger name="WebLogger">
			<level value="ALL"/>
		</logger>
		<appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
			<!-- name属性指定其名称,type则是log4net.Appender命名空间的一个类的名称,意思是,指定使用哪种介质-->
			<param name="File" value="Logger\"/>
			<!--//日志存放位置(这里的value值是一个Logger,表示在项目文件夹中创建一个名叫Logger的文件。也可以是value="c:\log.txt")-->
			<param name="AppendToFile" value="false"/>
			<!--//是否追加到文件-->
			<param name="MaxSizeRollBackups" value="100" />
			<!--备份文件的个数-->
			<param name="MaxFileSize" value="10240" />
			<!--当个日志文件的最大大小-->
			<param name="StaticLogFileName" value="false" />
			<!--是否使用静态文件名-->
			<param name="RollingStyle" value="Date"/>
			<!--//变换的形式为日期-->
			<param name="DatePattern" value="&quot;&quot;yyyyMMddHH&quot;.txt&quot;"/>
			<!--//生成格式;每天生成一个日志-->
			<param name="StaticLogFileName" value="false"/>
			<!--//日志文件名,是否固定不变-->
			<layout type="log4net.Layout.PatternLayout,log4net">
				<!--错误日志布局-->
				<!--<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/>-->
				<param name="ConversionPattern" value="%d [%t] [%-5p] - %m%n"/>
				<!--
          %m(message):输出的日志消息,如ILog.Debug(…)输出的一条消息 
          %n(new line):换行 
          %d(datetime):输出当前语句运行的时刻 
          %r(run time):输出程序从运行到执行到当前语句时消耗的毫秒数 
          %t(thread id):当前语句所在的线程ID 
          %p(priority): 日志的当前优先级别,即DEBUG、INFO、WARN…等 
          %c(class):当前日志对象的名称,例如: 
          %f(file):输出语句所在的文件名。 
          %l(line):输出语句所在的行号。 
          %数字:表示该项的最小长度,如果不够,则用空格填充,如“%-5level”表示level的最小宽度是5个字符,如果实际长度不够5个字符则以空格填充。
        -->
			</layout>
		</appender>
		<!--//这种配置,是将日志写入到文本文件当中-->
	</log4net>
</configuration>

添加一个名为Log4NetHelper的类


    public class Log4NetHelper
    {

        private static readonly log4net.ILog _Logger4net = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        RichTextBox richTextBox;

        static Log4NetHelper _instance;

        public static Log4NetHelper Instance()
        {
            if (_instance == null)
            {
                _instance = new Log4NetHelper();
            }
            return _instance;
        }

        private Log4NetHelper()
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string path = Path.Combine(baseDirectory, "log4net.config");
            XmlConfigurator.ConfigureAndWatch(new FileInfo(path));
        }

        public void Init(RichTextBox richTextBox)//该方法绑定需要显示日志的控件,这里绑定的是richtextbox
        {
            this.richTextBox = richTextBox;
        }
        #region [ 参数 ]
        public bool IsDebugEnabled
        {
            get { return _Logger4net.IsDebugEnabled; }
        }
        public bool IsInfoEnabled
        {
            get { return _Logger4net.IsInfoEnabled; }
        }
        public bool IsWarnEnabled
        {
            get { return _Logger4net.IsWarnEnabled; }
        }
        public bool IsErrorEnabled
        {
            get { return _Logger4net.IsErrorEnabled; }
        }
        public bool IsFatalEnabled
        {
            get { return _Logger4net.IsFatalEnabled; }
        }
        #endregion

        #region [ 接口方法 ]

        #region [ Debug ]

        public void Debugf(string format, params object[] args)
        {
            if (this.IsDebugEnabled)
            {
                this.Log(LogLevel.Debug, format, args);
            }
        }

        public void Debugf(string format, Exception exception, params object[] args)
        {
            if (this.IsDebugEnabled)
            {
                this.Log(LogLevel.Debug, string.Format(format, args), exception);
            }
        }
        #endregion

        #region [ Info ]

        public void Infof(string format, params object[] args)
        {
            if (this.IsInfoEnabled)
            {
                this.Log(LogLevel.Info, format, args);
                this.PrintLog(format, LogLevel.Info);
            }
        }

        public void Infof(string format, Exception exception, params object[] args)
        {
            if (this.IsInfoEnabled)
            {
                this.Log(LogLevel.Info, string.Format(format, args), exception);
                this.PrintLog(format, LogLevel.Info);
            }
        }
        #endregion

        #region  [ Warn ]


        public void Warnf(string format, params object[] args)
        {
            if (this.IsWarnEnabled)
            {
                this.Log(LogLevel.Warn, format, args);
            }
        }

        public void Warnf(string format, Exception exception, params object[] args)
        {
            if (this.IsWarnEnabled)
            {
                this.Log(LogLevel.Warn, string.Format(format, args), exception);
            }
        }
        #endregion

        #region  [ Error ]


        public void Errorf(string format, params object[] args)
        {
            if (this.IsErrorEnabled)
            {
                this.Log(LogLevel.Error, format, args);
                this.PrintLog(format, LogLevel.Error, System.Drawing.Color.Red);
            }
        }

        public void Errorf(string format, Exception exception, params object[] args)
        {
            if (this.IsErrorEnabled)
            {
                this.Log(LogLevel.Error, string.Format(format, args), exception);
                this.PrintLog(format, LogLevel.Error, System.Drawing.Color.Red);
            }
        }
        #endregion

        #region  [ Fatal ]


        public void Fatalf(string format, params object[] args)
        {
            if (this.IsFatalEnabled)
            {
                this.Log(LogLevel.Fatal, format, args);
            }
        }

        public void Fatalf(string format, Exception exception, params object[] args)
        {
            if (this.IsFatalEnabled)
            {
                this.Log(LogLevel.Fatal, string.Format(format, args), exception);
            }
        }
        #endregion
        #endregion

        #region [ 内部方法 ]
        /// <summary>
        /// 输出普通日志
        /// </summary>
        /// <param name="level"></param>
        /// <param name="format"></param>
        /// <param name="args"></param>
        private void Log(LogLevel level, string format, params object[] args)
        {
            switch (level)
            {
                case LogLevel.Debug:
                    _Logger4net.DebugFormat(format, args);
                    break;
                case LogLevel.Info:
                    _Logger4net.InfoFormat(format, args);
                    break;
                case LogLevel.Warn:
                    _Logger4net.WarnFormat(format, args);
                    break;
                case LogLevel.Error:
                    _Logger4net.ErrorFormat(format, args);
                    break;
                case LogLevel.Fatal:
                    _Logger4net.FatalFormat(format, args);
                    break;
            }
        }

        /// <summary>
        /// 格式化输出异常信息
        /// </summary>
        /// <param name="level"></param>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        private void Log(LogLevel level, string message, Exception exception)
        {
            switch (level)
            {
                case LogLevel.Debug:
                    _Logger4net.Debug(message, exception);
                    break;
                case LogLevel.Info:
                    _Logger4net.Info(message, exception);
                    break;
                case LogLevel.Warn:
                    _Logger4net.Warn(message, exception);
                    break;
                case LogLevel.Error:
                    _Logger4net.Error(message, exception);
                    break;
                case LogLevel.Fatal:
                    _Logger4net.Fatal(message, exception);
                    break;
            }
        }

        private void PrintLog(string info, LogLevel level)
        {
            if (richTextBox != null)
            {
                var infoFomart = string.Format("{0}-[{1}]-{2}\r\n", DateTime.Now.ToString("yyyy-MM-dd-HH:mm:fff"), level, info);
                richTextBox.BeginInvoke(new Action(() =>
                {
                    richTextBox.AppendText(infoFomart);
                }));
            }
        }
        private void PrintLog(string info, LogLevel level, Color color)
        {
            if (richTextBox != null)
            {
                var infoFomart = string.Format("{0}-[{1}]-{2}\r\n", DateTime.Now.ToString("yyyy-MM-dd-HH:mm:fff"), level, info);
                richTextBox.BeginInvoke(new Action(() =>
                {
                    richTextBox.SelectionColor = color;
                    richTextBox.AppendText(infoFomart);
                }));
            }
        }
        #endregion
    }


    #region [ enum: LogLevel ]
    /// <summary>
    /// 日志级别
    /// </summary>
    public enum LogLevel
    {
        Debug,
        Info,
        Warn,
        Error,
        Fatal
    }
    #endregion

winform用法,绑定richtextbox

 Log4NetHelper slog = Log4NetHelper.Instance();//声明对象

        private void Form1_Load(object sender, EventArgs e)
        {
            slog.Init(this.richTextBox1);//绑定需要显示日志的控件



            slog.Infof("程序加载完成");//书写日志
      
        }

注意事项:

复制到输出目录一定要改成始终复制!!!!!!!!!!!

标签:log4net,string,format,C#,void,args,用法,LogLevel,public
From: https://www.cnblogs.com/yuan99977/p/17655326.html

相关文章

  • TypeScript(TS)JavaScript(JS)中的所有循环方法
    for循环:for(leti=0;i<array.length;i++){//循环体}for…of循环:for(constelementofarray){//循环体}forEach方法:array.forEach((element)=>{//循环体});map方法:constnewArray=array.map((element)=>{//对......
  • 三、利用 Docker-Slim 缩小 Docker 镜像大小
    有时项目构建出来的Docker大小挺大的,找了好几个缩小Docker镜像的方法,在这里分享一个很棒的方法来优化和缩小Docker镜像并减小镜像体积大小。Docker-SlimDocker-Slim不会更改Docker容器映像中的任何内容并将其缩小多达30倍。Docker-Slim将通过使用各种分析技术了解您的......
  • 什么是 Backwards-compatible update releases
    Backwards-compatibleupdatereleases,也被称为“向后兼容的更新发布”,是软件开发和维护中的一个关键概念。它指的是在软件系统中进行更新或升级时,确保新版本的软件能够与旧版本的软件保持兼容,不会破坏已有的功能和接口,从而使得用户能够平滑地升级而无需进行大规模的改动。这个概......
  • docker想保留ip和端口其他的不要,想把这个变成linux的命令怎么做?
    docker想保留ip和端口其他的不要,想把这个变成linux的命令怎么做?dockerps只会显示这样一坨东西,看ip和端口又不好看456746ec7581moxi/mogu_blog_nacos"/usr/sbin/init"12hoursagoUp12hours0.0.0.0:465->465/tcp,:::465->465/tcp,0.0.0.0:3306->3306/tcp,:......
  • CF1837F
    原题翻译首先看到最大值最小就想到二分答案当我们二分了一个\(x\),我们考虑到恰好等于\(k\)的宣发不太好选,不如直接取得越多越好,换言之枚举分界点,看前后缀在选的数之和\(\leqx\)的情况下最多能选多少个,再合并而选数的过程可以用堆来维护前缀没有被选到数的最小值最终复杂度\(......
  • Tomcat与JavaWeb开发
    安装Tomcat&JDK安装时候选择tomcat软件版本要与程序开发使用的版本一致。jdk版本要进行与tomcat保持一致。准备2个linux虚拟机,一个运行nginx进行负载均衡一个用来运行tomcat第一步:安装JDKJDK官网地址:https://www.oracle.com/java/technologies/downloads/##下载JDK......
  • vs code 使用plug in s
    gitblamegitlens pylance Pylance是由Microsoft开发的Python语言服务器,用于提供快速准确的代码完成、类型检查和其他高级功能,可在多个代码编辑器中使用,例如VisualStudioCode(VSCode)。Pylance使用LanguageServerProtocol(LSP)与编辑器进行通信,从而实现跨平台支持......
  • 手把手教你Linux CentOS 8 安装MySQL 8
     安装步骤我所使用的Linux版本是CentOS8,在CentOS8上安装MySQL的步骤:启用MySQL8.0存储库首先,您需要启用MySQL8.0存储库。为此,请下载和安装MySQL的存储库包:sudodnfinstallhttps://dev.mysql.com/get/mysql80-community-release-el8-1.noarch.rpm安装MyS......
  • Docker下搭建Redis集群
    一、Redis集群方案的简单介绍Redis集群的方案一般分为三种:哈希取余分区一致性哈希算法分区哈希槽分区(本文介绍的就是这种) 1、哈希取余分区:优点:简单粗暴,只要提前预估好数据量,然后规划好节点,例如:3台、30台、300台节点,就能保证未来一段时间内的数据支撑。 缺点:事先规......
  • ICC - Route
    1.关于RouteRoute的主要目标满足timing的要求,如setup/hold/removal/recovery等。满足DRC的要求,例如:transition/capacitance,以及不能有short/open。Route绕线规则standardcell的pgrail可以采用M1,M2,M3。standardcell的pin脚一般采用M1.WidthandSpacingRu......