How to stop log4net from logging and release the last file

纵饮孤独 提交于 2019-12-12 12:16:40

问题


I'm using log4net in C# Win Form App and I have start/stop toggle button -

When I click "start" the log4net config are loaded and the log file is created - That is working.

But now I want to add the option to click "stop" button, for stopping the logger and of course release the file so I could open it with openFileDialog that I have in my app for reading the log file text with StreamReader to show the log file on a multiline textbox.


回答1:


You can modify the Threshold during runtime. To stop logging set it to Off. I have already shown how this works in this answer.




回答2:


Stopping log4net during runtime requires modifying its config file's:

<level value="ALL" />

to

<level value="INFO" />

If you can't change the config file you should define a proxy for log.debug():

static public class LogDebugProxy
{
    static public bool LogDebug = false;
    static public void debug(log4net.ILog log)
    {
        if (LogDebug)
            log.debug();
    }
}

Then replace log.debug() with LogDebugProxy.debug(log) in your entire project.

Now, you can Enable / Disable it by it's proxy.




回答3:


This works for me to read the log4net log-file:

            string text;
            var fileStream = new FileStream(@"C:\logs\yourLogFile.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
            {
                text = streamReader.ReadToEnd();
                MessageBox.Show(this, text);
            }


来源:https://stackoverflow.com/questions/55235209/how-to-stop-log4net-from-logging-and-release-the-last-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!