10458

log4net write single file for each call to log.info

I have been using log4net to capture any exceptions which occur during my applications running, which is working perfectly, I then created my own static Method which was responsible for capturing the failed XML object which was intended to provide further reading to compliment the log entry.

public static void WriteReceiptToXml(Exception ex, string XmlReceipt) { if (XmlReceipt != null) { string filename = ConfigurationManager.AppSettings["XmlReceiptPath"] + "/ReceiptXml" + DateTime.Now.ToString("ddMMyyhhmmss") + ".xml"; File.WriteAllText(filename, XmlReceipt); Logger.Error(string.Format("The Xml Receipt was written to {0}", filename)); } else Logger.Error("The Xml Receipt was empty so no document was created. Please reference the Payment request XML"); }

This worked well, however a more experienced colleague suggested that <strong>this was abit of a code smell</strong> and that I was effectively re-inventing the wheel, as I am already using log4net this task should be handled by it too.

At this point I created a new appender in the Web.config file (below) and filtered it on the INFO level, what I realised then was that as soon as I ran the application, log4net would create the XML file regardless of whether the catch block caught the exception and would leave it empty if no error occurred, which is obviously not what I want.

<appender name="ReceiptXmlAppender" type="log4net.Appender.FileAppender" > <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <file type="log4net.Util.PatternString" value="App_Data/ReceiptXml/Receipt-%date{yyyy-MM-dd_HH-mm-ss}.xml"/> <appendToFile value="false" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%m" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="INFO"/> <param name="LevelMax" value="INFO"/> </filter> </appender>

In summary what I want is:

    <li>log4net to only create the XML upon the INFO method being called in my catch block</li> <li>1 file to be created every time I call LOG.INFO</li> <li>The file must be datetime stamped</li> <li>I need to know the file name of the XML document created so that I can append this to actual log file as a supplement to the stack trace.</li> </ul>

    Answer1:

    If you use the basic FileAppender or one of its derivatives you are out of luck; the file is created as soon as the appender is initialized in the ActivateOptions() method. From what I see you need a custom FileAppender that will handle all your business rules. It would need to

      <li>override the default ActivateOptions method to prevent file creation</li> <li>override the Append method to create a new timestamped file when a message is logged</li> <li>use data passed in the LoggingEvent class (you have some properties available on the class) to retrieve the filename; you have to determine the filename before logging.</li> </ul>

      Unless you want to benefit from behavior it already implements(impersonation for example), I'd recommend skipping inheritance from the FileAppender class and inherit directly from the TextWriterAppender class.

Recommend

  • Apply style to first element in a row of similar elements
  • int.TryParse vs. other methods for determining if a char contains an int
  • Creating a subscription based website in ASP.NET
  • Does naming an instance variable with underscore as a prefix have any side effects in Cocoa (Objecti
  • htaccess assisting a php file
  • Install4j - How can I install the MSVC++ Redistributable Binary if needed?
  • PHP mysql SELECT QUERY with an Or
  • Rails - storing search query/result
  • How to pass data between viewcontrollers
  • Ext.getCmp(id) or Ext.ComponentQuery.query(attribute)
  • Retrieving large number of rows (more than 10 mil) in asp.net mvc application
  • Flash Button (Creating a menu page with flash buttons to open SWF Files)
  • Avoiding concurrency of Stored Procedures
  • How to reduce size of git repository after accidental push of large file size?
  • Show item of the day
  • LINQ Query to find all tags?
  • Use of multiple threads in a Java program and vs need to create Swing objects on EDT
  • Transforming multiindex to row-wise multi-dimensional NumPy array.
  • Vista focus issue when invoking Microsoft Word spell check from Oracle Forms
  • How can I ensure Realm schema is identical across Android and iOS?
  • Class implementation in a header file == bad style? [duplicate]
  • Is there a way to call library thread-local init/cleanup on thread creation/destruction?
  • Single django queryset to get n adjacent items
  • Criterion causing memory consumption to explode, no CAFs in sight
  • Laravel 4 routing not working due to .htaccess file?
  • Two Tables Serving as one Model in Rails
  • Implicit joins and Where in Doctrine - how?
  • Button text different than value submitted in query string
  • How to define and use opencv mat of user type
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • How would I use PHP exceptions to define a redirect?
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • Symfony2: How to get request parameter
  • log4net write single file for each call to log.info
  • Error creating VM instance in Google Compute Engine
  • Getting error when using KSoap library to consume .NET web services
  • Exception on Android 4.0 `android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode)`