Search code examples
c#mysqlsqllog4netadonetappender

Log4Net AdoNetAppender- truncate table / delete old records / limit DB size


What would be a simple way to effectively limit the size of the table Log4Net logs in to?

Something like deleting old records, or deleting when the total number of records reaches a predefined limit, or when the table (or DB) size reaches a size limit

(edit) since we have customers with both types of tagged DB (MySQL / MSSQL) a single point solution would be better from a maintenance POV.

we thought about using some code (with NHibernate) to periodically do what @samy suggested. but a performance-effective Log4Net solution is always better.


Solution

  • I'm going to assume you want to do it entirely from log4net; if you don't, then either

    • use a cron task that will delete data older than x days at your desired interval
    • use a trigger that can react to the insertion of new data by log4net

    These methods would be much cleaner than the following.

    Since the AdoNetAppender lets you specify the command text you could set up a second AdoNetAppender that would be triggered by the logging event along with your original appender. This second appender could then delete the data you don't want any more:

    CommandText="DELETE FROM Logs WHERE [date] < DATEADD(Hour,
    -6, GETDATE())"
    

    I think the logging framework should not be handling database maintenance so please consider letting MySQL do the work instead.