简体   繁体   English

如何在log4net中以编程方式更改日志文件路径?

[英]How to change the Log file path programmatically in log4net?

I am using %property% to set the output file path in the Log4Net configuration file. 我使用%property%来设置Log4Net配置文件中的输出文件路径。 A log file will be created in the APP data folder every time when the application launches. 每次应用程序启动时,都会在APP数据文件夹中创建一个日志文件。 I am using the Composite rolling style for rolling the files. 我正在使用Composite滚动样式来滚动文件。

But now my requirement is to roll/change the file path based on some user interactions in the application . 但现在我的要求是根据应用程序中的一些用户交互滚动/更改文件路径 How can I achieve this, can anyone suggest me to achieve this. 我怎样才能实现这一目标,任何人都可以建议我实现这一目标。

  1. How to roll the file in c# code. 如何在c#代码中滚动文件。 The expected behavior is similar to rolling based on Size and date. 预期行为类似于基于大小和日期的滚动。
  2. What is the c# code to change the output file path in Log4Net in between program execution? 在程序执行期间, 在Log4Net更改输出文件路径c#代码是什么?

Please let me know if my requirement is not clear. 如果我的要求不明确,请告诉我。

Thanks. 谢谢。

You have 2 questions: 你有两个问题:

  1. I'm not aware if this is possible. 我不知道这是否可行。 I guess the roll to next name is private in the rolling file appender. 我想在滚动文件appender中滚动到下一个名称是私有的。 You can look in the src to see if you can access it. 您可以查看src以查看是否可以访问它。 If not you can inherit from the RollingFileAppender and add your own implementation. 如果没有,您可以从RollingFileAppender继承并添加您自己的实现。 You can get the appenders on runtime by: 您可以通过以下方式获取运行时的appender:

code: 码:

  LogManager.GetRepository().GetAppenders();
  1. Using a property is the right way. 使用财产是正确的方法。 Your configuration should look like this: 您的配置应如下所示:

config: 配置:

 <appender name="YourAppender" type="log4net.Appender.RollingFileAppender"> 
    <file type="log4net.Util.PatternString" value="~/App_Data/%property{LogName}" />
 </appender>

Important is the type="log4net.Util.PatternString" . 重要的是type="log4net.Util.PatternString" Set the property before initializing log4net. 在初始化log4net之前设置属性。

log4net.GlobalContext.Properties["LogName"] = name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM