c# log4net 在代码中动态设置日志到指定路径?

2 篇文章 0 订阅
2 篇文章 0 订阅

在log4net中,BasicConfigurator类是用于配置基本日志记录器的,而Configure是此类的方法。

BasicConfigurator.Configure(_repository, appender)BasicConfigurator.Configure(appender)之间的主要区别在于它们接受的参数类型。

  1. BasicConfigurator.Configure(_repository, appender):这个方法通常在log4net库的某些版本中使用,其中第一个参数是一个ILoggerRepository对象,它是log4net中日志记录器存储库的实例,用于存储和管理日志记录器。第二个参数是一个Appender对象,它是用于配置日志如何被记录的组件。
  2. BasicConfigurator.Configure(appender):这个方法是较新的log4net版本中的推荐使用的方法。它只有一个参数,即一个Appender对象。在这种情况下,Appender对象应该包含有关如何配置和附加日志记录器所需的所有信息。

在大多数情况下,你应该使用 BasicConfigurator.Configure(appender),因为它是一个更简洁的方法,可以在没有显式创建 ILoggerRepository 实例的情况下进行配置。如果你的应用程序需要使用特定的 ILoggerRepository 实现(例如,如果你需要将日志记录到数据库或远程位置),则可以使用 BasicConfigurator.Configure(_repository, appender)

// 单个日志文件动态创建
public static class Logger
{
    public static void SetLogFile(string para)
    {
        RollingFileAppender appender = new RollingFileAppender();
        appender.Name = "RollingLogFileAppender";
        appender.File = AppDomain.CurrentDomain.BaseDirectory + $"Logs\\{para}.log";
        appender.DatePattern = "-yyyyMMdd".log"";
        appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
        appender.AppendToFile = true;
        appender.MaxSizeRollBackups = 5;
        appender.MaximumFileSize = "50MB";
        appender.StaticLogFileName = true;
        PatternLayout layout = new PatternLayout();
        layout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
        layout.ActivateOptions();
        appender.Layout = layout;
        appender.ActivateOptions();
        BasicConfigurator.Configure(appender);
   }

    public static void InitLogger(string para)
    {
        ILog fileLogger = LogManager.GetLogger("Logger");
        SetLogFile(para);
    }
}

    //动态的创建日志实例,将根据不同名称创建多个日志文件
    public static ILog SetLogFile(string portName)
    {
            RollingFileAppender appender = new RollingFileAppender();
            appender.Name = $"RollingLogFileAppender_{portName}";
            appender.File = AppDomain.CurrentDomain.BaseDirectory + $"Logs\\HVPS1pt2--{DateTime.Now.ToString("yyyyMMdd")}--{portName}.log";
            appender.DatePattern = "-yyyyMMdd".log"";
            appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
            appender.AppendToFile = true;// 如果文件存在,新的日志将追加到文件中,而不是覆盖文件
            appender.MaxSizeRollBackups = 5;
            appender.MaximumFileSize = "500MB";
            appender.StaticLogFileName = true;
            PatternLayout layout = new PatternLayout();
            layout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            appender.Layout = layout;// 设置日志的格式
            var filter = new LevelMatchFilter { LevelToMatch = Level.All };
            filter.ActivateOptions();
            appender.AddFilter(filter);
            appender.ActivateOptions();// 激活选项
            //创建实例,第一个参数是一个ILoggerRepository对象,它是log4net中日志记录器存储库的实例,必须有此实例才能动态创建多个日志文件
            var repositoryName = $"{portName}.Repository";
            ILoggerRepository _repository = LoggerManager.CreateRepository(repositoryName);
            BasicConfigurator.Configure(_repository, appender);
            return LogManager.GetLogger(_repository.Name, portName);
    }

    public static void InitLogger(string para)
    {
        ILog fileLogger = SetLogFile("para");
    }

参考:https://www.cnblogs.com/-dawn/p/8598566.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using opc_Library; namespace Files { /// /// Form1 的摘要说明。 /// public class Form1 : System.Windows.Forms.Form { write_log write_log = new write_log(); private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1; private System.Windows.Forms.Button button1; private System.Windows.Forms.RichTextBox richTextBox1; private System.IO.FileSystemWatcher fileSystemWatcher1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Label label2; /// /// 必需的设计器变量。 /// private System.ComponentModel.Container components = null; public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// /// 清理所有正在使用的资源。 /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows 窗体设计器生成的代码 /// /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog(); this.button1 = new System.Windows.Forms.Button(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.fileSystemWatcher1 = new System.IO.FileSystemWatcher(); this.button2 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.fileSystemWatcher1)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(120, 16); this.label1.TabIndex = 0; this.label1.Text = "文件夹全路径名: "; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(8, 40); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(320, 21); this.textBox1.TabIndex = 1; this.textBox1.Text = "C:\\"; // // button1 // this.button1.Location = new System.Drawing.Point(232, 8); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(96, 23); this.button1.TabIndex = 2; this.button1.Text = "浏览文件夹"; this.button1.Click += new System.EventHandler(this.button1_Click_1); // // richTextBox1 // this.richTextBox1.Location = new System.Drawing.Point(8, 88); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.Size = new System.Drawing.Size(320, 136); this.richTextBox1.TabIndex = 3; this.richTextBox1.Text = ""; // // fileSystemWatcher1 // this.fileSystemWatcher1.EnableRaisingEvents = true; this.fileSystemWatcher1.SynchronizingObject = this; this.fileSystemWatcher1.Changed += new System.IO.FileSystemEventHandler(this.fileSystemWatcher1_Changed); this.fileSystemWatcher1.Created += new System.IO.FileSystemEventHandler(this.fileSystemWatcher1_Created); this.fileSystemWatcher1.Deleted += new System.IO.FileSystemEventHandler(this.fileSystemWatcher1_Deleted); this.fileSystemWatcher1.Renamed += new System.IO.RenamedEventHandler(this.fileSystemWatcher1_Renamed); // // button2 // this.button2.Location = new System.Drawing.Point(232, 64); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(96, 23); this.button2.TabIndex = 5; this.button2.Text = "开始监视"; this.button2.Click += new System.EventHandler(this.button2_Click); // // label2 // this.label2.Location = new System.Drawing.Point(8, 72); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(120, 16); this.label2.TabIndex = 4; this.label2.Text = "文件系统变化情况: "; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(336, 230);
C# log4net是一个优秀的第三方日志框架。通过引用log4net的dll并配置一些基本参数,开发者可以很容易地将日志信息输出到各种不同的目标,例如文本、数据库、Windows日志、邮件、内存缓冲区等目标。 在你提供的代码,我们可以看到log4net的使用。首先,你需要在程序集配置log4net,使用XmlConfigurator特性指定配置文件路径和扩展名,并设置Watch属性为true,以便在配置文件发生更改时重新加载配置。 然后,你可以在需要记录日志的地方使用log4net日志输出功能。在Utils命名空间下的Logger类,有三个方法可供使用: 1. WriteInfo(string info)方法用于记录正常日志信息。它会将传入的信息输出到控制台,并且如果允许信息记录,则使用loginfo来记录信息。 2. WriteError(string error)方法用于记录错误日志信息。它会将传入的错误信息输出到控制台,并且如果允许错误记录,则使用logerror来记录错误信息。 3. WriteError(string info, Exception ex)方法用于记录带有异常信息的错误日志。它会将传入的信息输出到控制台,并且如果允许错误记录,则使用logerror来记录信息和异常。 在Log4netTest命名空间下的Program类,我们可以看到Logger类的使用示例。在Main方法,我们可以看到调用了Logger.WriteInfo和Logger.WriteError方法来记录日志信息。 总结起来,C# log4net是一个方便易用的日志框架,可以帮助开发者将日志信息输出到各种不同的目标。通过配置log4net和调用Logger类的方法,开发者可以轻松记录正常日志和错误日志,并且可以记录带有异常信息的错误日志

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值