0

How to use multiple appender in same log4net config file? Also provide how to dynamically select appenders in C# code to write logs.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Vetrivel mp
  • 1,214
  • 1
  • 14
  • 29

1 Answers1

2

You can configure multiple appenders very easily. For example like this:

<appender name="ConsoleAppender" ...
   ...
</appender>

<appender name="RollingFileAppender" ...
   ...
</appender>

<root>
   <level value="ALL" />
   <appender-ref ref="ConsoleAppender" />
   <appender-ref ref="RollingFileAppender" />
</root>

The second part is harder to answer: The idea is not to select an appender and write to it. Normally you use loggers and simply write whatever you think is useful at an appropriate log level. You do not care where your log messages are written to: This is for the system administrator to decide (IMHO).

It is actually possible to use different appenders for different loggers. A system administrator might decide to log all errors in a YourApp.Security namespace to a SMTP appender while the rest simply goes to a database or a file. More information on loggers can be found in this excellent tutorial: http://www.beefycode.com/post/Log4Net-Tutorial-pt-5-Using-Logger-Objects.aspx

It is however possible to create appenders in code (sample code can be found here) but the question is if you really want to do this. Example: If you want to send an email in certain situations then I suggest not use log4net. Instead you simply create and send the email in your own code.

Community
  • 1
  • 1
Stefan Egli
  • 17,398
  • 3
  • 54
  • 75
  • thanks for reply. but if log4net supports multiple appenders to log in multiple source. then why can not we decide which appender to use at runtime? my serious doubt is second part i know already we can have multiple appender in same file. but my question why we can not select any one at runtime using c# code? – Vetrivel mp Mar 22 '12 at 11:27
  • you can decide what appenders a logger uses, but I still wonder why you would want to do this and based on your requirements, if there is not an other solution. have a look here (should get you started): http://mail-archives.apache.org/mod_mbox/logging-log4net-user/200602.mbox/%3CDDEB64C8619AC64DBC074208B046611C769745@kronos.neoworks.co.uk%3E – Stefan Egli Mar 27 '12 at 10:35
  • Also before i read this article, i create different levels with different appender. for example, for debug=> fileappender, for error=>adoappender. so based on my flag i select where to store. if(flag=="file"){log.debug()} else if(flag=="db"){log.error()} – Vetrivel mp Mar 28 '12 at 08:39
  • can refer this also http://stackoverflow.com/questions/769983/how-to-configure-log4net-programmatically-from-scratch-no-config – Vetrivel mp Mar 28 '12 at 10:04