Click here to Skip to main content
15,912,837 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
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());
            }

        }
Posted
Updated 22-Jan-17 0:30am
v3
Comments
Afzaal Ahmad Zeeshan 22-Jan-17 3:59am    
Do they support asynchronous pattern?

If not, please consider using Task objects to run saving process in the background.
kumarravishankar 22-Jan-17 5:42am    
no its not support
kumarravishankar 22-Jan-17 5:44am    
can u please suggest me with sample of code for this
Afzaal Ahmad Zeeshan 22-Jan-17 6:30am    
Kindly see Solution 1 for a sample. Surely you would require to rewrite maximum of it in order to fit your needs.

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.
C#
// 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.
}

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)[^].
 
Share this answer
 
v2
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!!!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900