简体   繁体   中英

Etiquette and/or optimal way to write to a file

I am currently questioning a snippet of code, in regards to its effectivity and resource drain. The following is a global logging utility method that will be compiled into a DLL. The method may be accessed concurrently.

private static void Log(string logType,
                        string severity,
                        object sender,
                        string format,
                        params object[] args)
    {
        if (Logger._logLock.WaitOne(250))
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(Logger._activityLogPath, true))
                {
                    if (logType != "RAW")
                    {
                        sw.Write("{0} {1} {2} ",
                            DateTime.Now,
                            logType,
                            severity);
                    }

                    sw.WriteLine(format, args);
                }
            }
            finally
            {
                Logger._logLock.ReleaseMutex();
            }
        }
    }

What is bothering me is the "using" block that is going to be creating a stream from the same file, each and every time something is logged (multi-calls per second). I am aware of file caching so I'm not entirely sure that reinstalling the stream is too big of an issue (unnecessary stream-buffer initialization however?). I was toying with the idea of adding the StreamWriter as a variable in the Logger class, but I also want to make sure that the writer is properly closed or flushed if the unit is improperly hard-shutdown. The end-users are known to just shut the unit off. I'm trying to find the balance between safety and speed and was just hoping for a bit of insight. Thanks.

a) Yes, creating a stream every time is not really efficient. You might consider, for example, that you collect messages in some sort of collection and write/append this collection in a fixed interval, may be from another thread, to a file... That way you wont need to wait 250ms since the message could be append to the collection and the thread will consume the content of the collection. You should also keep the stream open - the way you do it might fail if some other application locks the file... If you flush after writing a hard-shutdown should not effect the content of the log-file.

b) There are numerous logging frameworks that are well tested, flexible and have awesome performance... Why re-invent the wheel?

I also want to make sure that the writer is properly closed or flushed if the unit is improperly hard-shutdown.

It won't be properly closed if the user turns the device off while the stream is not flushed, whether you use using or not (the critical time span may be shorter with using and without manually flushing).

Instead of creating a new StreamWriter each time, create it once and flush it after writing. But be aware that you need some kind of hardware (read: buffer battery, UPS) if you want to be 100% sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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