Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

c# - Log4NET AdoNetAppender connection string reference

I want to use Log4NET to log into my DB and following some tutorials I see that I have to configure a connection string for the DAO appender.

I already have a connection string in my web.config for DB connection so I'm wondering if I can reference that instead of setting a new one.

I usually change my connection string to switch from dev DB to production DB so it could be very useful to share the same connection parameters.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit: since this was posted, log4net now supports specifying the connection string name in the config. From https://issues.apache.org/jira/browse/LOG4NET-88 -

This adds a new "connectionStringName" attribute (and corresponding ConnectionStringName) property to the AdoNetAppender class. This is a reference to a connection string within the <ConnectionStrings> section of an App.config or Web.config file.

There's an example in this answer.

If you don't have the connection string defined in the <ConnectionStrings> section then you can set the connection string at runtime using this class:

You invoke SetConnectionString with the connection string just after you've configured log4net.

However, there are a couple of things I would note:

Log4net database appenders don't like being created without a connection string, and throw an (internal) error - and during unit testing, I've seen tests take more than 10 seconds when given a fake connection string.

public static class LogConfigurator
{
   public static void SetConnectionString(string connectionString)
   {
        Hierarchy logHierarchy = log4net.LogManager.GetRepository() as Hierarchy;

        if (logHierarchy == null)
        {
            throw new InvalidOperationException
               ("Can't set connection string as hierarchy is null.");
        }

        var appender = logHierarchy.GetAppenders()
                                   .OfType<AdoNetAppender>()
                                   .SingleOrDefault();

        if (appender == null)
        {
            throw new InvalidOperationException
              ("Can't locate a database appender");
        }

        appender.ConnectionString = connectionString;
        appender.ActivateOptions();
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...