Can log4net output Json?












6















I've seen a couple extensions for log4net that claim to create json to the log file, but the format is never valid json, meaning the collection is not in an array and not coma separated. Am I using it wrong or is there just no way to use log4net with json?



<appender name="SessionFileAppender" type="log4net.Appender.FileAppender">
<file value="Session.log" />
<appendToFile value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type='log4net.Layout.SerializedLayout, log4net.Ext.Json'>
<decorator type='log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json' />
<default />
<remove value='message' />
<member value='message:messageobject' />
</layout>
</appender>


Output is:



{"date":"2017-01-29T13:45:50.7345813-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Loading new UI instance"}
{"date":"2017-01-29T13:45:50.7380842-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Loading internal localization file"}
{"date":"2017-01-29T13:45:50.7510970-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Initializing UI"}


which is close, but not really valid json.










share|improve this question



























    6















    I've seen a couple extensions for log4net that claim to create json to the log file, but the format is never valid json, meaning the collection is not in an array and not coma separated. Am I using it wrong or is there just no way to use log4net with json?



    <appender name="SessionFileAppender" type="log4net.Appender.FileAppender">
    <file value="Session.log" />
    <appendToFile value="false" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type='log4net.Layout.SerializedLayout, log4net.Ext.Json'>
    <decorator type='log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json' />
    <default />
    <remove value='message' />
    <member value='message:messageobject' />
    </layout>
    </appender>


    Output is:



    {"date":"2017-01-29T13:45:50.7345813-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Loading new UI instance"}
    {"date":"2017-01-29T13:45:50.7380842-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Loading internal localization file"}
    {"date":"2017-01-29T13:45:50.7510970-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Initializing UI"}


    which is close, but not really valid json.










    share|improve this question

























      6












      6








      6


      2






      I've seen a couple extensions for log4net that claim to create json to the log file, but the format is never valid json, meaning the collection is not in an array and not coma separated. Am I using it wrong or is there just no way to use log4net with json?



      <appender name="SessionFileAppender" type="log4net.Appender.FileAppender">
      <file value="Session.log" />
      <appendToFile value="false" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type='log4net.Layout.SerializedLayout, log4net.Ext.Json'>
      <decorator type='log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json' />
      <default />
      <remove value='message' />
      <member value='message:messageobject' />
      </layout>
      </appender>


      Output is:



      {"date":"2017-01-29T13:45:50.7345813-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Loading new UI instance"}
      {"date":"2017-01-29T13:45:50.7380842-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Loading internal localization file"}
      {"date":"2017-01-29T13:45:50.7510970-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Initializing UI"}


      which is close, but not really valid json.










      share|improve this question














      I've seen a couple extensions for log4net that claim to create json to the log file, but the format is never valid json, meaning the collection is not in an array and not coma separated. Am I using it wrong or is there just no way to use log4net with json?



      <appender name="SessionFileAppender" type="log4net.Appender.FileAppender">
      <file value="Session.log" />
      <appendToFile value="false" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type='log4net.Layout.SerializedLayout, log4net.Ext.Json'>
      <decorator type='log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json' />
      <default />
      <remove value='message' />
      <member value='message:messageobject' />
      </layout>
      </appender>


      Output is:



      {"date":"2017-01-29T13:45:50.7345813-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Loading new UI instance"}
      {"date":"2017-01-29T13:45:50.7380842-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Loading internal localization file"}
      {"date":"2017-01-29T13:45:50.7510970-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Initializing UI"}


      which is close, but not really valid json.







      c# json wpf log4net






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 29 '17 at 18:53









      WobblesWobbles

      1,9221333




      1,9221333
























          4 Answers
          4






          active

          oldest

          votes


















          6














          download log4net.Ext.Json nuget package



          add following config settings to app.config/web.config files



          <log4net>
          <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
          <file value="logslog-file-name.json" />
          <rollingStyle value="Date" />
          <datePattern value="yyyy-MM-dd" />
          <PreserveLogFileNameExtension value="true" />
          <staticLogFileName value="false" />
          <appendToFile value="true" />
          <maxSizeRollBackups value="10" />
          <dateTimeStrategy
          type="log4net.Appender.RollingFileAppender+UniversalDateTime" />

          <!--text formatted log4net logging-->
          <!--<layout type="log4net.Layout.PatternLayout">
          --><!--check conversion patterns from
          https://logging.apache.org/log4net/--><!--
          --><!--<conversionPattern value="%utcdate{ABSOLUTE} UTC %c{1} - %m%n"
          />--><!--
          <conversionPattern value="%date [%thread] %-5level %logger -
          %message%newline" />
          </layout>-->

          <!--json formatted log4net logging-->
          <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
          <decorator type="log4net.Layout.Decorators.StandardTypesDecorator,
          log4net.Ext.Json" />
          <member value="date:date" />
          <member value="level:level" />
          <member value="logger:logger" />
          <member value="message:messageObject" />
          <member value="exception:exception" />
          </layout>
          </appender>
          <root>
          <!--Options are "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" and
          "OFF".-->
          <level value="DEBUG" />
          <appender-ref ref="RollingFile" />
          </root>
          </log4net>


          here is a sample call with ninject



          Kernel = new StandardKernel(); 
          Kernel.Bind<ILog>().ToMethod(c =>
          LogManager.GetLogger(typeof(YourClassName))).InSingletonScope();
          var log = Kernel.Get<ILog>();
          log.debug("testing log4net json");





          share|improve this answer

































            4














            The solution is basic enough, I wrote my own Appender that stored data in a collection, then serialized the collection with Json.net as needed. This also gives me the ability to view the log in the app and bind to it aswell so added bonus.



            public class CollectionAppender : AppenderSkeleton
            {
            public static ObservableCollection<LogItem> logData = new ObservableCollection<LogItem>();
            protected override void Append(LoggingEvent loggingEvent)
            {
            logData.Add(new LogItem(loggingEvent));
            }
            }

            public class LogItem
            {
            public string Logger { get; private set; }
            public string Level { get; private set; }
            public string Message { get; private set; }
            public DateTime Timestamp { get; private set; }
            public Exception ExceptionData { get; private set; }

            public bool ShouldSerializeExceptionData() //This keeps things tidy when using Json.net for non exemption entries.
            {
            return ExceptionData != null;
            }

            public LogItem(LoggingEvent data)
            {
            Logger = data.LoggerName;
            Level = data.Level.DisplayName;
            Message = data.RenderedMessage;
            Timestamp = data.TimeStamp;
            ExceptionData = data.ExceptionObject;
            }
            }





            share|improve this answer
























            • That's a nice solution! Is log4net still actively maintained, it would be nice to have it in there - maybe wroth a contrib?

              – Yves Schelpe
              Jan 29 '17 at 20:52











            • I use this approach in testing scenarios. If that is all you need, simple enough.

              – Rbjz
              May 6 '18 at 16:44



















            2














            It outputs each line as separate JSON record, as it does with 1 line logs.
            You can take line by line and parse, or you can add your surrounding and a comman after each } and that would do it.






            share|improve this answer
























            • If I still have to iterate and re-parse a file after the fact then it kind of defeats the purpose.

              – Wobbles
              Jan 29 '17 at 18:59






            • 1





              Your are right @Wobbles, but its kind of hard even for them since logs open-write-close streams so i think it will be tricky to maintain the json format, unless the file is in memory and get overridden each time a record is written.

              – MoustafaS
              Jan 29 '17 at 19:00











            • didn't consider that, ill see if there is a way to directly serialize the ILog collection then as needed

              – Wobbles
              Jan 29 '17 at 19:02











            • If you didnt find a solution and you are using it as it is in c# or JS, then i suggect you add [ and ] and replace all ( } ) with ( }, ) and it will work with only one parse, heavy but will do the trick. @Wobbles

              – MoustafaS
              Jan 29 '17 at 19:04








            • 1





              It could be achieved on appender level. log4net.Ext.Json works as a layout for individual log events. If you go for string replacement as @MoustafaS recommended, please put coma before every new line instead of } because the graph can be nested or the data may contain } while new lines are escaped by default.

              – Rbjz
              May 6 '18 at 16:18





















            -2














            Yes, do this in the log4net.config file.



                <conversionPattern

            value="{&quot;EntryDate&quot;:&quot;%date{ddd MMM dd HH:mm:ss zzz yyyy}&quot;,

            &quot;Level&quot;:&quot;%level&quot;,

            &quot;Logger&quot;:&quot;%logger&quot;,

            &quot;Message&quot;:&quot;%message&quot;}

            %newline" />





            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41924684%2fcan-log4net-output-json%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              6














              download log4net.Ext.Json nuget package



              add following config settings to app.config/web.config files



              <log4net>
              <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
              <file value="logslog-file-name.json" />
              <rollingStyle value="Date" />
              <datePattern value="yyyy-MM-dd" />
              <PreserveLogFileNameExtension value="true" />
              <staticLogFileName value="false" />
              <appendToFile value="true" />
              <maxSizeRollBackups value="10" />
              <dateTimeStrategy
              type="log4net.Appender.RollingFileAppender+UniversalDateTime" />

              <!--text formatted log4net logging-->
              <!--<layout type="log4net.Layout.PatternLayout">
              --><!--check conversion patterns from
              https://logging.apache.org/log4net/--><!--
              --><!--<conversionPattern value="%utcdate{ABSOLUTE} UTC %c{1} - %m%n"
              />--><!--
              <conversionPattern value="%date [%thread] %-5level %logger -
              %message%newline" />
              </layout>-->

              <!--json formatted log4net logging-->
              <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
              <decorator type="log4net.Layout.Decorators.StandardTypesDecorator,
              log4net.Ext.Json" />
              <member value="date:date" />
              <member value="level:level" />
              <member value="logger:logger" />
              <member value="message:messageObject" />
              <member value="exception:exception" />
              </layout>
              </appender>
              <root>
              <!--Options are "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" and
              "OFF".-->
              <level value="DEBUG" />
              <appender-ref ref="RollingFile" />
              </root>
              </log4net>


              here is a sample call with ninject



              Kernel = new StandardKernel(); 
              Kernel.Bind<ILog>().ToMethod(c =>
              LogManager.GetLogger(typeof(YourClassName))).InSingletonScope();
              var log = Kernel.Get<ILog>();
              log.debug("testing log4net json");





              share|improve this answer






























                6














                download log4net.Ext.Json nuget package



                add following config settings to app.config/web.config files



                <log4net>
                <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
                <file value="logslog-file-name.json" />
                <rollingStyle value="Date" />
                <datePattern value="yyyy-MM-dd" />
                <PreserveLogFileNameExtension value="true" />
                <staticLogFileName value="false" />
                <appendToFile value="true" />
                <maxSizeRollBackups value="10" />
                <dateTimeStrategy
                type="log4net.Appender.RollingFileAppender+UniversalDateTime" />

                <!--text formatted log4net logging-->
                <!--<layout type="log4net.Layout.PatternLayout">
                --><!--check conversion patterns from
                https://logging.apache.org/log4net/--><!--
                --><!--<conversionPattern value="%utcdate{ABSOLUTE} UTC %c{1} - %m%n"
                />--><!--
                <conversionPattern value="%date [%thread] %-5level %logger -
                %message%newline" />
                </layout>-->

                <!--json formatted log4net logging-->
                <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
                <decorator type="log4net.Layout.Decorators.StandardTypesDecorator,
                log4net.Ext.Json" />
                <member value="date:date" />
                <member value="level:level" />
                <member value="logger:logger" />
                <member value="message:messageObject" />
                <member value="exception:exception" />
                </layout>
                </appender>
                <root>
                <!--Options are "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" and
                "OFF".-->
                <level value="DEBUG" />
                <appender-ref ref="RollingFile" />
                </root>
                </log4net>


                here is a sample call with ninject



                Kernel = new StandardKernel(); 
                Kernel.Bind<ILog>().ToMethod(c =>
                LogManager.GetLogger(typeof(YourClassName))).InSingletonScope();
                var log = Kernel.Get<ILog>();
                log.debug("testing log4net json");





                share|improve this answer




























                  6












                  6








                  6







                  download log4net.Ext.Json nuget package



                  add following config settings to app.config/web.config files



                  <log4net>
                  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
                  <file value="logslog-file-name.json" />
                  <rollingStyle value="Date" />
                  <datePattern value="yyyy-MM-dd" />
                  <PreserveLogFileNameExtension value="true" />
                  <staticLogFileName value="false" />
                  <appendToFile value="true" />
                  <maxSizeRollBackups value="10" />
                  <dateTimeStrategy
                  type="log4net.Appender.RollingFileAppender+UniversalDateTime" />

                  <!--text formatted log4net logging-->
                  <!--<layout type="log4net.Layout.PatternLayout">
                  --><!--check conversion patterns from
                  https://logging.apache.org/log4net/--><!--
                  --><!--<conversionPattern value="%utcdate{ABSOLUTE} UTC %c{1} - %m%n"
                  />--><!--
                  <conversionPattern value="%date [%thread] %-5level %logger -
                  %message%newline" />
                  </layout>-->

                  <!--json formatted log4net logging-->
                  <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
                  <decorator type="log4net.Layout.Decorators.StandardTypesDecorator,
                  log4net.Ext.Json" />
                  <member value="date:date" />
                  <member value="level:level" />
                  <member value="logger:logger" />
                  <member value="message:messageObject" />
                  <member value="exception:exception" />
                  </layout>
                  </appender>
                  <root>
                  <!--Options are "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" and
                  "OFF".-->
                  <level value="DEBUG" />
                  <appender-ref ref="RollingFile" />
                  </root>
                  </log4net>


                  here is a sample call with ninject



                  Kernel = new StandardKernel(); 
                  Kernel.Bind<ILog>().ToMethod(c =>
                  LogManager.GetLogger(typeof(YourClassName))).InSingletonScope();
                  var log = Kernel.Get<ILog>();
                  log.debug("testing log4net json");





                  share|improve this answer















                  download log4net.Ext.Json nuget package



                  add following config settings to app.config/web.config files



                  <log4net>
                  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
                  <file value="logslog-file-name.json" />
                  <rollingStyle value="Date" />
                  <datePattern value="yyyy-MM-dd" />
                  <PreserveLogFileNameExtension value="true" />
                  <staticLogFileName value="false" />
                  <appendToFile value="true" />
                  <maxSizeRollBackups value="10" />
                  <dateTimeStrategy
                  type="log4net.Appender.RollingFileAppender+UniversalDateTime" />

                  <!--text formatted log4net logging-->
                  <!--<layout type="log4net.Layout.PatternLayout">
                  --><!--check conversion patterns from
                  https://logging.apache.org/log4net/--><!--
                  --><!--<conversionPattern value="%utcdate{ABSOLUTE} UTC %c{1} - %m%n"
                  />--><!--
                  <conversionPattern value="%date [%thread] %-5level %logger -
                  %message%newline" />
                  </layout>-->

                  <!--json formatted log4net logging-->
                  <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
                  <decorator type="log4net.Layout.Decorators.StandardTypesDecorator,
                  log4net.Ext.Json" />
                  <member value="date:date" />
                  <member value="level:level" />
                  <member value="logger:logger" />
                  <member value="message:messageObject" />
                  <member value="exception:exception" />
                  </layout>
                  </appender>
                  <root>
                  <!--Options are "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" and
                  "OFF".-->
                  <level value="DEBUG" />
                  <appender-ref ref="RollingFile" />
                  </root>
                  </log4net>


                  here is a sample call with ninject



                  Kernel = new StandardKernel(); 
                  Kernel.Bind<ILog>().ToMethod(c =>
                  LogManager.GetLogger(typeof(YourClassName))).InSingletonScope();
                  var log = Kernel.Get<ILog>();
                  log.debug("testing log4net json");






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 6 '18 at 17:49









                  Rbjz

                  1,44411532




                  1,44411532










                  answered Jan 19 '18 at 17:19









                  oetzioetzi

                  5911




                  5911

























                      4














                      The solution is basic enough, I wrote my own Appender that stored data in a collection, then serialized the collection with Json.net as needed. This also gives me the ability to view the log in the app and bind to it aswell so added bonus.



                      public class CollectionAppender : AppenderSkeleton
                      {
                      public static ObservableCollection<LogItem> logData = new ObservableCollection<LogItem>();
                      protected override void Append(LoggingEvent loggingEvent)
                      {
                      logData.Add(new LogItem(loggingEvent));
                      }
                      }

                      public class LogItem
                      {
                      public string Logger { get; private set; }
                      public string Level { get; private set; }
                      public string Message { get; private set; }
                      public DateTime Timestamp { get; private set; }
                      public Exception ExceptionData { get; private set; }

                      public bool ShouldSerializeExceptionData() //This keeps things tidy when using Json.net for non exemption entries.
                      {
                      return ExceptionData != null;
                      }

                      public LogItem(LoggingEvent data)
                      {
                      Logger = data.LoggerName;
                      Level = data.Level.DisplayName;
                      Message = data.RenderedMessage;
                      Timestamp = data.TimeStamp;
                      ExceptionData = data.ExceptionObject;
                      }
                      }





                      share|improve this answer
























                      • That's a nice solution! Is log4net still actively maintained, it would be nice to have it in there - maybe wroth a contrib?

                        – Yves Schelpe
                        Jan 29 '17 at 20:52











                      • I use this approach in testing scenarios. If that is all you need, simple enough.

                        – Rbjz
                        May 6 '18 at 16:44
















                      4














                      The solution is basic enough, I wrote my own Appender that stored data in a collection, then serialized the collection with Json.net as needed. This also gives me the ability to view the log in the app and bind to it aswell so added bonus.



                      public class CollectionAppender : AppenderSkeleton
                      {
                      public static ObservableCollection<LogItem> logData = new ObservableCollection<LogItem>();
                      protected override void Append(LoggingEvent loggingEvent)
                      {
                      logData.Add(new LogItem(loggingEvent));
                      }
                      }

                      public class LogItem
                      {
                      public string Logger { get; private set; }
                      public string Level { get; private set; }
                      public string Message { get; private set; }
                      public DateTime Timestamp { get; private set; }
                      public Exception ExceptionData { get; private set; }

                      public bool ShouldSerializeExceptionData() //This keeps things tidy when using Json.net for non exemption entries.
                      {
                      return ExceptionData != null;
                      }

                      public LogItem(LoggingEvent data)
                      {
                      Logger = data.LoggerName;
                      Level = data.Level.DisplayName;
                      Message = data.RenderedMessage;
                      Timestamp = data.TimeStamp;
                      ExceptionData = data.ExceptionObject;
                      }
                      }





                      share|improve this answer
























                      • That's a nice solution! Is log4net still actively maintained, it would be nice to have it in there - maybe wroth a contrib?

                        – Yves Schelpe
                        Jan 29 '17 at 20:52











                      • I use this approach in testing scenarios. If that is all you need, simple enough.

                        – Rbjz
                        May 6 '18 at 16:44














                      4












                      4








                      4







                      The solution is basic enough, I wrote my own Appender that stored data in a collection, then serialized the collection with Json.net as needed. This also gives me the ability to view the log in the app and bind to it aswell so added bonus.



                      public class CollectionAppender : AppenderSkeleton
                      {
                      public static ObservableCollection<LogItem> logData = new ObservableCollection<LogItem>();
                      protected override void Append(LoggingEvent loggingEvent)
                      {
                      logData.Add(new LogItem(loggingEvent));
                      }
                      }

                      public class LogItem
                      {
                      public string Logger { get; private set; }
                      public string Level { get; private set; }
                      public string Message { get; private set; }
                      public DateTime Timestamp { get; private set; }
                      public Exception ExceptionData { get; private set; }

                      public bool ShouldSerializeExceptionData() //This keeps things tidy when using Json.net for non exemption entries.
                      {
                      return ExceptionData != null;
                      }

                      public LogItem(LoggingEvent data)
                      {
                      Logger = data.LoggerName;
                      Level = data.Level.DisplayName;
                      Message = data.RenderedMessage;
                      Timestamp = data.TimeStamp;
                      ExceptionData = data.ExceptionObject;
                      }
                      }





                      share|improve this answer













                      The solution is basic enough, I wrote my own Appender that stored data in a collection, then serialized the collection with Json.net as needed. This also gives me the ability to view the log in the app and bind to it aswell so added bonus.



                      public class CollectionAppender : AppenderSkeleton
                      {
                      public static ObservableCollection<LogItem> logData = new ObservableCollection<LogItem>();
                      protected override void Append(LoggingEvent loggingEvent)
                      {
                      logData.Add(new LogItem(loggingEvent));
                      }
                      }

                      public class LogItem
                      {
                      public string Logger { get; private set; }
                      public string Level { get; private set; }
                      public string Message { get; private set; }
                      public DateTime Timestamp { get; private set; }
                      public Exception ExceptionData { get; private set; }

                      public bool ShouldSerializeExceptionData() //This keeps things tidy when using Json.net for non exemption entries.
                      {
                      return ExceptionData != null;
                      }

                      public LogItem(LoggingEvent data)
                      {
                      Logger = data.LoggerName;
                      Level = data.Level.DisplayName;
                      Message = data.RenderedMessage;
                      Timestamp = data.TimeStamp;
                      ExceptionData = data.ExceptionObject;
                      }
                      }






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jan 29 '17 at 19:56









                      WobblesWobbles

                      1,9221333




                      1,9221333













                      • That's a nice solution! Is log4net still actively maintained, it would be nice to have it in there - maybe wroth a contrib?

                        – Yves Schelpe
                        Jan 29 '17 at 20:52











                      • I use this approach in testing scenarios. If that is all you need, simple enough.

                        – Rbjz
                        May 6 '18 at 16:44



















                      • That's a nice solution! Is log4net still actively maintained, it would be nice to have it in there - maybe wroth a contrib?

                        – Yves Schelpe
                        Jan 29 '17 at 20:52











                      • I use this approach in testing scenarios. If that is all you need, simple enough.

                        – Rbjz
                        May 6 '18 at 16:44

















                      That's a nice solution! Is log4net still actively maintained, it would be nice to have it in there - maybe wroth a contrib?

                      – Yves Schelpe
                      Jan 29 '17 at 20:52





                      That's a nice solution! Is log4net still actively maintained, it would be nice to have it in there - maybe wroth a contrib?

                      – Yves Schelpe
                      Jan 29 '17 at 20:52













                      I use this approach in testing scenarios. If that is all you need, simple enough.

                      – Rbjz
                      May 6 '18 at 16:44





                      I use this approach in testing scenarios. If that is all you need, simple enough.

                      – Rbjz
                      May 6 '18 at 16:44











                      2














                      It outputs each line as separate JSON record, as it does with 1 line logs.
                      You can take line by line and parse, or you can add your surrounding and a comman after each } and that would do it.






                      share|improve this answer
























                      • If I still have to iterate and re-parse a file after the fact then it kind of defeats the purpose.

                        – Wobbles
                        Jan 29 '17 at 18:59






                      • 1





                        Your are right @Wobbles, but its kind of hard even for them since logs open-write-close streams so i think it will be tricky to maintain the json format, unless the file is in memory and get overridden each time a record is written.

                        – MoustafaS
                        Jan 29 '17 at 19:00











                      • didn't consider that, ill see if there is a way to directly serialize the ILog collection then as needed

                        – Wobbles
                        Jan 29 '17 at 19:02











                      • If you didnt find a solution and you are using it as it is in c# or JS, then i suggect you add [ and ] and replace all ( } ) with ( }, ) and it will work with only one parse, heavy but will do the trick. @Wobbles

                        – MoustafaS
                        Jan 29 '17 at 19:04








                      • 1





                        It could be achieved on appender level. log4net.Ext.Json works as a layout for individual log events. If you go for string replacement as @MoustafaS recommended, please put coma before every new line instead of } because the graph can be nested or the data may contain } while new lines are escaped by default.

                        – Rbjz
                        May 6 '18 at 16:18


















                      2














                      It outputs each line as separate JSON record, as it does with 1 line logs.
                      You can take line by line and parse, or you can add your surrounding and a comman after each } and that would do it.






                      share|improve this answer
























                      • If I still have to iterate and re-parse a file after the fact then it kind of defeats the purpose.

                        – Wobbles
                        Jan 29 '17 at 18:59






                      • 1





                        Your are right @Wobbles, but its kind of hard even for them since logs open-write-close streams so i think it will be tricky to maintain the json format, unless the file is in memory and get overridden each time a record is written.

                        – MoustafaS
                        Jan 29 '17 at 19:00











                      • didn't consider that, ill see if there is a way to directly serialize the ILog collection then as needed

                        – Wobbles
                        Jan 29 '17 at 19:02











                      • If you didnt find a solution and you are using it as it is in c# or JS, then i suggect you add [ and ] and replace all ( } ) with ( }, ) and it will work with only one parse, heavy but will do the trick. @Wobbles

                        – MoustafaS
                        Jan 29 '17 at 19:04








                      • 1





                        It could be achieved on appender level. log4net.Ext.Json works as a layout for individual log events. If you go for string replacement as @MoustafaS recommended, please put coma before every new line instead of } because the graph can be nested or the data may contain } while new lines are escaped by default.

                        – Rbjz
                        May 6 '18 at 16:18
















                      2












                      2








                      2







                      It outputs each line as separate JSON record, as it does with 1 line logs.
                      You can take line by line and parse, or you can add your surrounding and a comman after each } and that would do it.






                      share|improve this answer













                      It outputs each line as separate JSON record, as it does with 1 line logs.
                      You can take line by line and parse, or you can add your surrounding and a comman after each } and that would do it.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jan 29 '17 at 18:56









                      MoustafaSMoustafaS

                      1,588717




                      1,588717













                      • If I still have to iterate and re-parse a file after the fact then it kind of defeats the purpose.

                        – Wobbles
                        Jan 29 '17 at 18:59






                      • 1





                        Your are right @Wobbles, but its kind of hard even for them since logs open-write-close streams so i think it will be tricky to maintain the json format, unless the file is in memory and get overridden each time a record is written.

                        – MoustafaS
                        Jan 29 '17 at 19:00











                      • didn't consider that, ill see if there is a way to directly serialize the ILog collection then as needed

                        – Wobbles
                        Jan 29 '17 at 19:02











                      • If you didnt find a solution and you are using it as it is in c# or JS, then i suggect you add [ and ] and replace all ( } ) with ( }, ) and it will work with only one parse, heavy but will do the trick. @Wobbles

                        – MoustafaS
                        Jan 29 '17 at 19:04








                      • 1





                        It could be achieved on appender level. log4net.Ext.Json works as a layout for individual log events. If you go for string replacement as @MoustafaS recommended, please put coma before every new line instead of } because the graph can be nested or the data may contain } while new lines are escaped by default.

                        – Rbjz
                        May 6 '18 at 16:18





















                      • If I still have to iterate and re-parse a file after the fact then it kind of defeats the purpose.

                        – Wobbles
                        Jan 29 '17 at 18:59






                      • 1





                        Your are right @Wobbles, but its kind of hard even for them since logs open-write-close streams so i think it will be tricky to maintain the json format, unless the file is in memory and get overridden each time a record is written.

                        – MoustafaS
                        Jan 29 '17 at 19:00











                      • didn't consider that, ill see if there is a way to directly serialize the ILog collection then as needed

                        – Wobbles
                        Jan 29 '17 at 19:02











                      • If you didnt find a solution and you are using it as it is in c# or JS, then i suggect you add [ and ] and replace all ( } ) with ( }, ) and it will work with only one parse, heavy but will do the trick. @Wobbles

                        – MoustafaS
                        Jan 29 '17 at 19:04








                      • 1





                        It could be achieved on appender level. log4net.Ext.Json works as a layout for individual log events. If you go for string replacement as @MoustafaS recommended, please put coma before every new line instead of } because the graph can be nested or the data may contain } while new lines are escaped by default.

                        – Rbjz
                        May 6 '18 at 16:18



















                      If I still have to iterate and re-parse a file after the fact then it kind of defeats the purpose.

                      – Wobbles
                      Jan 29 '17 at 18:59





                      If I still have to iterate and re-parse a file after the fact then it kind of defeats the purpose.

                      – Wobbles
                      Jan 29 '17 at 18:59




                      1




                      1





                      Your are right @Wobbles, but its kind of hard even for them since logs open-write-close streams so i think it will be tricky to maintain the json format, unless the file is in memory and get overridden each time a record is written.

                      – MoustafaS
                      Jan 29 '17 at 19:00





                      Your are right @Wobbles, but its kind of hard even for them since logs open-write-close streams so i think it will be tricky to maintain the json format, unless the file is in memory and get overridden each time a record is written.

                      – MoustafaS
                      Jan 29 '17 at 19:00













                      didn't consider that, ill see if there is a way to directly serialize the ILog collection then as needed

                      – Wobbles
                      Jan 29 '17 at 19:02





                      didn't consider that, ill see if there is a way to directly serialize the ILog collection then as needed

                      – Wobbles
                      Jan 29 '17 at 19:02













                      If you didnt find a solution and you are using it as it is in c# or JS, then i suggect you add [ and ] and replace all ( } ) with ( }, ) and it will work with only one parse, heavy but will do the trick. @Wobbles

                      – MoustafaS
                      Jan 29 '17 at 19:04







                      If you didnt find a solution and you are using it as it is in c# or JS, then i suggect you add [ and ] and replace all ( } ) with ( }, ) and it will work with only one parse, heavy but will do the trick. @Wobbles

                      – MoustafaS
                      Jan 29 '17 at 19:04






                      1




                      1





                      It could be achieved on appender level. log4net.Ext.Json works as a layout for individual log events. If you go for string replacement as @MoustafaS recommended, please put coma before every new line instead of } because the graph can be nested or the data may contain } while new lines are escaped by default.

                      – Rbjz
                      May 6 '18 at 16:18







                      It could be achieved on appender level. log4net.Ext.Json works as a layout for individual log events. If you go for string replacement as @MoustafaS recommended, please put coma before every new line instead of } because the graph can be nested or the data may contain } while new lines are escaped by default.

                      – Rbjz
                      May 6 '18 at 16:18













                      -2














                      Yes, do this in the log4net.config file.



                          <conversionPattern

                      value="{&quot;EntryDate&quot;:&quot;%date{ddd MMM dd HH:mm:ss zzz yyyy}&quot;,

                      &quot;Level&quot;:&quot;%level&quot;,

                      &quot;Logger&quot;:&quot;%logger&quot;,

                      &quot;Message&quot;:&quot;%message&quot;}

                      %newline" />





                      share|improve this answer




























                        -2














                        Yes, do this in the log4net.config file.



                            <conversionPattern

                        value="{&quot;EntryDate&quot;:&quot;%date{ddd MMM dd HH:mm:ss zzz yyyy}&quot;,

                        &quot;Level&quot;:&quot;%level&quot;,

                        &quot;Logger&quot;:&quot;%logger&quot;,

                        &quot;Message&quot;:&quot;%message&quot;}

                        %newline" />





                        share|improve this answer


























                          -2












                          -2








                          -2







                          Yes, do this in the log4net.config file.



                              <conversionPattern

                          value="{&quot;EntryDate&quot;:&quot;%date{ddd MMM dd HH:mm:ss zzz yyyy}&quot;,

                          &quot;Level&quot;:&quot;%level&quot;,

                          &quot;Logger&quot;:&quot;%logger&quot;,

                          &quot;Message&quot;:&quot;%message&quot;}

                          %newline" />





                          share|improve this answer













                          Yes, do this in the log4net.config file.



                              <conversionPattern

                          value="{&quot;EntryDate&quot;:&quot;%date{ddd MMM dd HH:mm:ss zzz yyyy}&quot;,

                          &quot;Level&quot;:&quot;%level&quot;,

                          &quot;Logger&quot;:&quot;%logger&quot;,

                          &quot;Message&quot;:&quot;%message&quot;}

                          %newline" />






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Aug 22 '18 at 14:42









                          JEuvinJEuvin

                          3161421




                          3161421






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41924684%2fcan-log4net-output-json%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              這個網誌中的熱門文章

                              Xamarin.form Move up view when keyboard appear

                              Post-Redirect-Get with Spring WebFlux and Thymeleaf

                              Anylogic : not able to use stopDelay()