0

How do I write an entry to a log4net file regardless which log level is set at that moment? 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?

Frank
  • 431
  • 1
  • 5
  • 25
  • If you set the LogLevel to `Error` are you sure you want to have a notification about the LogLevel in the Logs? – quadroid Apr 17 '18 at 11:02
  • @Console: Yes. With my log, I want to be able to explain why there is nog more 'INFO' and 'DEBUG' logging after I changed to another level. – Frank Apr 17 '18 at 11:05
  • You can try to just log it in the level you currently switched to. – quadroid Apr 17 '18 at 12:02

2 Answers2

1

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.

Bozhidar Stoyneff
  • 3,576
  • 1
  • 18
  • 28
  • Your link is for NLOG, but Log4Net has something similar: http://geekswithblogs.net/rakker/archive/2007/08/22/114900.aspx – Frank Apr 17 '18 at 11:07
  • And following you suggestion: As long as there is no 'better' solution, I temporary set the level to INFO, write an INFO entry and set the level to the required level. – Frank Apr 17 '18 at 11:09
  • Yeah, it is similar in log4net. Sorry for the confusion, but the conception remains. – Bozhidar Stoyneff Apr 17 '18 at 11:20
-1

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
João Silva
  • 531
  • 4
  • 21
  • 40