May 26, 2011

Write you messages in a separated file

It is not always easy with a sitecore "out of the box" to know witch messages come from your custom code and witch messages come from sitecore himself.
Here is a small tip to write you custom messages in a separated file:

First of all, we will prefix all our messages with a custom prefix "SH - " in my case:
Log.Info("SH - My message", typeof(MyObject));
Log.Error("SH - My message", typeof(MyObject));
...

And then to write it in a custom log file change in the web.config in the log4net section:
<appender name="MyFileAppender" type="log4net.Appender.SitecoreLogFileAppender, Sitecore.Logging">
    <file value="$(dataFolder)/logs/mylog.{date}.txt" />
 <filter type="log4net.Filter.StringMatchFilter">
    <regexToMatch value="^SH .*" />
    </filter>
    <filter type="log4net.Filter.DenyAllFilter" />
    <appendToFile value="true" />
    <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%4t %d{ABSOLUTE} %-5p %m%n" />
    </layout>
</appender>
You will need to adapt the regex with your custom prefix of course.

And second point after the logFileAppender of sitecore add you custom one:
<root>
    <priority value="DEBUG"/>
    <appender-ref ref="LogFileAppender"/>
    <appender-ref ref="MyFileAppender" />
</root>

You have a lot of example of what you can do with log4net here: http://logging.apache.org/log4net/release/config-examples.html

2 commentaires:

  1. ATM I have implemented Alex Shyba's solution of sending all Sitecore logs to a table "Logs" in a separate DB. I am thinking of using your idea and extend it to write my own messages to a different table. Makes sense?
    By the way, I just noticed that you posted this just yesterday! What a perfect timing!!!

    ReplyDelete
  2. Ouf course it makes sense I remember the post of Alex Shyba I was very interesting and I think that it is not incompatible.
    To put the "basic" logs into SQL it is only some configuration (look at the official website of log4net)

    ReplyDelete