How to Log Client Ip, Browser Name and User Name using Log4net in asp.net?

六月ゝ 毕业季﹏ 提交于 2019-12-11 12:41:58

问题


I want to log Client IP Address, Browser Name and Windows Authenticated User Name using log4net library.

I'm trying in this way, but its not working.

So Please help me out.

Main issue is I don't know how to add multiple custom properties in log4net.

Please help me.

Server Side Code.

log4net.GlobalContext.Properties["Hostname"] = GetIP();
            log4net.GlobalContext.Properties["Browser"] =  HttpContext.Current.Request.Browser.Type;
            log4net.GlobalContext.Properties["username"] = HttpContext.Current.Request.LogonUserIdentity.Name;

Web.Config Setting:

<conversionPattern value="%date %property{Hostname, username, Browser} [%thread]&#xD;&#xA;          %-5level %logger - %message%newline"
                                           />

If any other setting is required, Please let me know.

Or is there any other way to do this, Please let me know.


回答1:


To give you a more 'elegant' solution for this: use ndc.

<conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" />

using Nested diagnostic context in code (NDC):

using(log4net.NDC.Push("["+GetIP() + " - " + HttpContext.Current.Request.Browser.Type + " - " + HttpContext.Current.Request.LogonUserIdentity.Name+"]")
{
    //your code
    //all log messages will contain the ndc string with the using.
}



回答2:


It can be done in this way, Its useful for others.

<conversionPattern value="%date [%property{Hostname}] [%property{UserName}] [%property{Browser}] [%property{WindowsLogin}] [%thread]&#xD;&#xA;          %-5level %logger - %message%newline"
                                           />


来源:https://stackoverflow.com/questions/24182013/how-to-log-client-ip-browser-name-and-user-name-using-log4net-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!