简体   繁体   English

无论设置了哪个级别,如何将行写到log4net日志文件?

[英]How do I write a line to a log4net log file, regardless which level is set?

How do I write an entry to a log4net file regardless which log level is set at that moment? 无论当时设置了哪种日志级别,如何将条目写入log4net文件? The only way I can assure a line will be added, is to add a 'Fatal' entry. 我可以确保添加一行的唯一方法是添加一个“致命”条目。 And that is ugly and will even fail if the level is set to 'Off'. 这很丑陋,如果将级别设置为“关”,甚至会失败。

For instance: I want to log that the log level was changed to 'Error'. 例如:我想记录该日志级别已更改为“错误”。 If I would use: 如果我要使用:

Logger.Log.Info($"LogLevel set to {logLevelText}");

Then this line will not be written if the level was just set to 'Error'. 然后,如果仅将级别设置为“错误”,则不会写入此行。

So, is there a way to just write a line to the log? 那么,有没有办法在日志中写一行呢?

Nope. 不。 You cannot write an entry, without a log level. 没有日志级别,您将无法编写条目。 You can however manipulate log levels at runtime. 但是,您可以在运行时操纵日志级别。 So you can set the log level momentarily to whatever you need, just to ensure your message is written to the log, then restore the original level. 因此,您可以随时将日志级别设置为所需的任何级别,只是确保您的消息已写入日志,然后恢复原始级别。 See this SO thread for details. 有关详细信息,请参见此SO线程

This is how I'm using it in my project. 这就是我在项目中使用它的方式。 Hope it help. 希望对您有所帮助。

private static readonly log4net.ILog rootlog = log4net.LogManager.GetLogger("rootLogger");

rootlog.Info(string.Format("Service [{0}] has started.", this.ServiceName)); // info msg

rootlog.Error(string.Format("Get Tasks Unsuccessfull: {0}", response.MessageValue)); // error msg

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

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