如何使用logfornet异步编写文件 [英] How to write a file asynchronously using logfornet

查看:97
本文介绍了如何使用logfornet异步编写文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用log4net dll在文件中编写日志信息,但我想使用log4net dll异步编写文件(比如使用async)。



我尝试过:



I am writing logging info in file using log4net dll, but I want to write the files asynchronously (like using async ) with using log4net dll.

What I have tried:

public static void WriteInfoToLog(string Message, string RequestID, MCashModel.MCashEnums.RequestResponseType type)
        {
            try
            {
                string file_Path = String.Empty;
                string directory_Path = "~/LogDetails/" + DateTime.Today.ToString("yyyy") + "/" + DateTime.Today.ToString("MM") + "/" + DateTime.Today.ToString("dd") + "/" + DateTime.Now.Hour.ToString();
                if (type == MCashEnums.RequestResponseType.Request)
                {
                    file_Path = directory_Path + "/RQ_" + RequestID + ".txt";
                }
                else if (type == MCashEnums.RequestResponseType.Response)
                {
                    file_Path = directory_Path + "/RQ_" + RequestID + ".txt";
                }

                if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(directory_Path)))
                {
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(directory_Path));
                }
                if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(file_Path)))
                {
                    File.Create(System.Web.HttpContext.Current.Server.MapPath(file_Path)).Close();
                }
                using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(file_Path)))
                {
                    w.WriteLine("\r\nLog Entry (InFo): ");
                    w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    string err = "URL : " + System.Web.HttpContext.Current.Request.Url.ToString() + "." +
                                  "\r\n XML: \r\n" + Message + ".";
                    //+  "\r\nStack Trace:" + stackTrace + ".";
                    w.WriteLine(err);
                    w.WriteLine("__________________________");
                    w.Flush();
                    w.Close();
                }
            }
            catch (Exception exObject)
            {
                LoggerHelper.LogMessage(exObject.ToString());
            }

        }

推荐答案

由于您的API没有提供任何异步方法来编写数据到文件,只有一种方法可以实现异步模式;使用任务对象。虽然你也可以使用Threads,但那会很复杂。这个概念是你可以在后台线程中运行任何返回 Task 的函数,或者至少从中释放你的主UI线程。因此,您将长时间运行的I / O代码封装在一个函数中,然后在代码中等待它。

Since your API does not provide any asynchronous approach to writing the data to the files, there is only one way to achieve asynchronous pattern; using Task object. Although you can also make use of Threads, but that will be complex. The concept is that you can run any function that returns Task in a background thread or at least release your main UI thread from it. So you encapsulate long running I/O code in a function, and then await it in your code.
// you will call this function.
public async void writeData() {
    // capture the data
    await _writeIo(data);
    // move onwards
}

private Task _writeIo(object data) {
    // your code to write the content.
}



会发生什么当控件到达 _writeIo 时,控件将向后移动,并等待该函数完成。有关此概念的更多信息,请阅读以下MSDN指南,使用异步和等待的异步编程(C#) [ ^ ]。



在MSDN上有一个可以使用的示例: Task.Run方法(Action)(System.Threading.Tasks) [ ^ ]。


What happens is that the control will move backwards when it hits the _writeIo, and will wait until that function completes. For more on this concept, please consider reading the following MSDN guide, Asynchronous Programming with async and await (C#)[^].

There is a sample, that you can use, on MSDN: Task.Run Method (Action) (System.Threading.Tasks)[^].


log4net,因为它不支持异步写作。 ..

您应该使用以下变体之一: NuGet Gallery | Log4Net.Async 2.0.3 [ ^ ]

另请阅读异步文件I / O [ ^在.NET中......]



我会补充一点,IO - 本质上(至少在当前操作系统中)是阻塞的,所以解决方案是将它包装在一个单独的线程中并继续使用主要的...这一切都很好,但是在日志记录的情况下,由于日志数据的可能数量(这可能是一个很大的问题)超过10000个并发用户)...

所以在某些情况下让一个用户等待日志比打开大量线程来处理非阻塞IO更好......

当然,人们必须仔细考虑记录什么以及何时记录!!!
log4net as is DOES NOT support async writings...
You should use one of the variants, like this: NuGet Gallery | Log4Net.Async 2.0.3[^]
Also read about Asynchronous File I/O[^] in .NET...

I would add to it, that IO - by its nature (at least in current OSes) is blocking, so the solution is wrapping it in a separate thread and continue with the main one... It is all good and nice, but in case of logging it can be very problematic, because of the possible volume of the log data (imagine a site with over 10000 concurrent users)...
So in some cases let one user wait for log is better, than opening large number of threads to handle non-blocking IO...
And of course, one have to think carefully what to log and when to log!!!


这篇关于如何使用logfornet异步编写文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆