Logging into text file or database

logging

When should I use database for logging and when text files?
I see that web servers and web frameworks (that your app uses internally) usually (always?) log requests and errors into text files by default. But I see that people who develop their app around those servers and frameworks sometimes log into database (even the main DB of the app, not some external one).
Also maybe there is a difference between debug logs and audit logs — I have read this classification somewhere on this site.

Best Answer

In very general terms, logging to a text file is much faster than logging to a database. That's the main aspect of logging you need to consider.

The reason you log to a DB is more likely to be because you want to query the results - searching for particular log info is easier in a DB, particularly if you log contextual information that can be used to group log entries together. It is also usually easier to access a central DB than a log file on a server which may be secured and not accessible.

The ideal would be to log locally to a file, and then migrate this data to a DB for inspection if needed afterwards.

Now auditing is a different beast altogether. While it is similar in concept to logging, audit is usually needed to be kept for a long time (unlike log files used for debugging or tracing that may be deleted at a whim). Audits are there to show important information. You log far less audit information and less often than normal logging so performance is not a concern. Its for this reason that the advantages of writing this audit info to a central DB are seen.

Related Topic