简体   繁体   中英

log4net custom log objects and appender

I'd like to extend log4net to accept custom log objects as parameter. For example:

        public class MyLogObject
    {
        public string PropA;
        public int PropB;
    }

    private MyLogObject entry = new MyLogObject() {PropA = "FooBar", PropB = 1};
    Log.Debug(entry);

... this should work similar to exceptions.

In the second step the custom log objects should be written into a database by a custom database appender. The custom database appender will be is similar to the ADONetAppender but with a few modifications like an internal buffered queue of log entries.

Does anyone know if this works with log4net and if there are any examples with may help me how to do it?

The properties of my log object and the database fields are fixed, so there is no need for making them configurable.

Update My idea was to configure log4net to use my custom "MyAppender" together with the custom renderer "MyRenderer". The renderer will return a simple SQL-insert-statement with is written to the database by the appender. Maybe there is a better way to do this.

You can store your custom object in the ThreadContext (or global context if that makes sense)

log4net.ThreadContext.Properties["MyLogObject"] = entry;

The property can be easily extracted in your appender. If you provide a "ToString()" override you can even print it using normal appenders and specifying a conversion pattern:

date %-5level %property{MyLogObject} - %message%newline

It would be a good idea to create an interface and a wrapper for log4net. Then you add methods that accepts your object as a parameter so that you can hide the details about setting the context.

Why not use the AdoNetAppender? The appender inherits built-in buffering capabilities from BufferingAppenderSkeleton .

If you don't require storing each property of the MyLogObject class in separate table columns you can override the ToString() method. The string will be used as value for the log %message%:

public class MyLogObject
{
    public string PropA;
    public int PropB;

    override public string ToString()
    {
        return PropA + " " + PropB;
    }
}

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