Startec
Startec

Reputation: 13206

Should writing logs to file be asynchronous?

The documentation for .NET says:

Logging should be so fast that it isn't worth the performance cost of asynchronous code.

However, I am accustomed to almost all I/O in C# being async.

This would include writing to a simple text file as part of my logging. I work on a realtime graphics application which means, even if the overall execution time is longer by using async functions, this would be preferable to any blocking operation.

Is the overhead of opening, writing and saving a file (steps required to log to a file) not worth the performance cost of asynchronous code in C# / .NET?

Upvotes: 2

Views: 1403

Answers (1)

John Wu
John Wu

Reputation: 52240

The complete quote is:

Logging should be so fast that it isn't worth the performance cost of asynchronous code. If a logging datastore is slow, don't write to it directly. Consider writing the log messages to a fast store initially, then moving them to the slow store later. For example, when logging to SQL Server, don't do so directly in a Log method, since the Log methods are synchronous. Instead, synchronously add log messages to an in-memory queue and have a background worker pull the messages out of the queue to do the asynchronous work of pushing data to SQL Server. [emphasis added]

link

What they are describing is actually asynchronous logging, with respect to the final storage medium. It's just that the logger methods themselves are not async. The logger methods write to an intermediary store synchronously, then an asynchronous (background) operation writes it to the final location, which in your case would be the filesystem. This is completely consistent with what you're describing as asynchronous logging.

Upvotes: 3

Related Questions