0

I am developing a library for my clients and I also need some way to know how consumers are using the library and get information on its usage analytics. In my library, I want to use Logstash Appender such that if I am logging any metrics info, it gets sent to our logstash pipeline.

How should I support this additional logging(for our analytics) such that it does not interfere with the logging setup of the library consumer. Does logging libraries like slf4j, log4j, logback-classic, util.logging support such use case where from inside the library I can configure separate appenders ?

1 Answers1

0

You can define as many appenders as you need and route your logging to any combination of them.

There is a tutorial somewhere with all of the log4j.xml configuration options. But these example snippets from my development configuration should complement it to give you ideas as to how to customize it for what you need.

   <!-- DEFAULT appender -->
   <appender name="FILE" class="net.cndc.log4j.appender.CndcDateRollingFileAppender">
      <param name="File" value="/work/appLogs/tomcat9-2020-test/apps.txt"/>
      <param name="MaxFileSize" value="100KB" /> <!-- 10KB for testing, raise to 200KB -->
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
      </layout>
   </appender>
    

   <!-- EMAIL appender -->
   <appender name="EMAIL" class="net.cndc.log4j.appender.CndcDateRollingFileAppender">
      <param name="File" value="/work/appLogs/tomcat9-2020-test/email.txt"/>
      <param name="MaxFileSize" value="1MB" /> 
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
      </layout>
   </appender>

   <!-- ============================== -->
   <!-- Append messages to the console -->
   <!-- ============================== -->

   <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
      <param name="Target" value="System.out"/>
      <param name="Threshold" value="DEBUG"/>

      <layout class="org.apache.log4j.PatternLayout">
         <!-- The default pattern: Date Priority [Category] Message\n -->
         <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c] %m%n"/>
      </layout>
   </appender>

This code at the bottom of the log4j.xml tells it to send all of the logging to the CONSOLE and FILE appenders:

   <root>
      <appender-ref ref="CONSOLE"/>
      <appender-ref ref="FILE"/>
   </root>

Finally, unqualified categories send things to CONSOLE and FILE, while specifically designating the appender send it to the EMAIL log.

   <category name="net.cndc">
      <priority value="DEBUG"/>
   </category>
   ... and others like this one for other packages

   <category name="net.cndc.ws.email" additivity="false">
      <priority value="INFO"/>
      <appender-ref ref="EMAIL" />
   </category>