简体   繁体   中英

log4net %property gets null after being set

I have setup log4Net ADONetAppender to a table called log.

The log4net gets configured on Application_Start() of the Global.asax.cs file.

The table and its inserts are typical

INSERT INTO log ([PCDate],[Thread],[Level],[Logger],[Message],[Exception]) 
    VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)

All what is different is that i have set my Logger to be the application user that is currently logged into the system.

This in the .config file.

<parameter>
   <parameterName value="@logger"/>
   <dbType value="String"/>
   <size value="255"/>
   <layout type="log4net.Layout.PatternLayout">
     <conversionPattern value="%property{userName}"/> 
   </layout>
</parameter>

I do the logging before any insert, update or delete of user-data records in a class responsible for handling that.

logger.Info(strquery); 

The message of the logger, is the insert/update or delete query. The logger gets set to the current application logged user eg Bob, ash etc on login and debugging validates that it gets set to that value.

log4net.ThreadContext.Properties["userName"] = userName;

I could alternatively put the above statement in every asp that will ultimately do the insert/add/delete but that is cumbersome we looking at 12 current file not to mention that this is not scale-able.

Where/why does the property value get set to null after ??
The table records look like this

在此处输入图片说明

This is happening because ThreadContext persists the username on the current thread , and as you can see from your logs the thread changes between calls: when you set the value on login, it's valid for the current request, but the next request gets a new thread and consequently a new ThreadContext and the value is gone.

If you store the username in the session, you can set the ThreadContext property in the Application_AcquireRequestState event in your Global.asax.cs file. Then it will be valid for the whole request.

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