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 type="log4net.Filter.DenyAllFilter" />
    <appendToFile value="true" />
    <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%4t %d{ABSOLUTE} %-5p %m%n" />
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:
    <priority value="DEBUG"/>
    <appender-ref ref="LogFileAppender"/>
    <appender-ref ref="MyFileAppender" />

You have a lot of example of what you can do with log4net here:

EDIT: You have an alternative syntaxt and more info about the filters here


  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!!!

  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)

  3. With the regular log4net you need to configure it using either



    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]

    Do you need something similar with Sitecore in order logging to work?

  4. You don't need to add anything else. Sitecore is allready taking car of it for you.

    Apparently the regexmathign doesn't work for me anymore but the following filter do the trick: