开发者

How to write a logger

So, I'd like to write a logger in c# for an app I'm working on. However, since I love efficiency, I don't wan开发者_Python百科t to be opening and closing a log file over and over again during execution.

I think I'd like to write all events to RAM and then write to the log file once when the app exits. Would this be a good practice? If so, how should I implement it?

If this is not a good practice, what would be?

(And I'm not using Windows' event log at this time.)


However, since I love efficiency, I don't want to be opening and closing a log file over and over again during execution

No. It's since you love premature optimizations.

I think I'd like to write all events to RAM and then write to the log file once when the app exits. Would this be a good practice? If so, how should I implement it?

If you love efficiency, why do you want to waste a lot of memory for log entries?

If this is not a good practice, what would be?

It is if you want to lose all logs when your application crashes (since it cannot write the log to disk then). Why did you create the log in the first place?


You'll have to think of some issues you might encounter:

  • System being shut down while your application runs -> no log files
  • An application crash might not invoke your write method
  • If the log grows large (how long does your application run?), you might get memory problems
  • If the log grows large, and there is not enough space on the drive, not a single log line will be written

You could simply keep the file open while your application runs (with at least FileShare.Read so you can monitor it), or consider writing batches of log lines, invoking the write method after a group of methods, or even using a timer.


Well if your app crashes, you lose all your logs. Better if you flush the logs to disk at an appropriate moment.. Lazy write:

Queue off the log entries to a seperate logger thread, (ie. store them in some class and queue the class instance to a producer-consumer queue). In the logger thread, wait on the input queue with a timeout. If a log entry comes in, store it in a local cache queue.

If (timeout fires) or (some high water mark of logs stored is reached) then write all cached log entries to the file and flush file buffers.

Rgds, Martin

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜