How do you log the machine name via log4net?
Asked Answered
B

2

45

I am using Log4Net with the AdoNetAppender to log messages from a simple systray application into a SQL Server 2005 database.

I want to log the machine name along with the log message because this application will be running on multiple machines and I need to know on which one the message originated.

But, I cannot find a way to expose this information via the log4net.Layout.PatternLayout that I am using with the appender.

Is there a way to log the machine name via log4net in this manner?

Borchardt answered 2/10, 2008 at 15:0 Comment(0)
B
92

You can use the pre-populated property log4net:HostName, for example:

<conversionPattern value="%property{log4net:HostName}" />

This way you don't need to populate the MDC.

Broad answered 2/10, 2008 at 16:40 Comment(2)
For future readers, I got my AdoNetAppender to work with this <parameter name="workstation"> <parameterName value="@workstation"/> <dbType value="String"/> <size value="256" /> <layout type="log4net.Layout.PatternLayout" value="%property{log4net:HostName}" /> </parameter>Rockey
Future readers. I ~think this comes from the FIELDS on this page : logging.apache.org/log4net/release/sdk/html/…Rockey
E
11

you can create a parameter similar to the following:

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

Then add this line before writing to the log: MDC.Set("machine", Environment.MachineName);

Evensong answered 2/10, 2008 at 15:23 Comment(1)
That worked perfectly. I knew it must have been something simple. Thanks.Borchardt

© 2022 - 2024 — McMap. All rights reserved.