log4net 2.0.8 pattern for client ip address - log4net

I tried to log ip address of the incoming request. I tried following configuration but it does not working for me its log in as "DEBUG".
Global.aspx
void Application_BeginRequest(object sender, EventArgs e)
{
log4net.ThreadContext.Properties["addr"] = Request.UserHostAddress;
}
RollingFileAppender
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%p{addr} %date [%thread] %-5level %logger - %message%newline"/>
</layout>
Log look like this
DEBUG 2018-11-20 06:22:50,328 [40] DEBUG Conference - loging successfully

Lowercase %p is a shortcut for %level.
To output a custom property, you should use uppercase %P
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%P{addr} %date [%thread] %-5level %logger - %message%newline"/>
</layout>
or the full keyword %property
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%property{addr} %date [%thread] %-5level %logger - %message%newline"/>
</layout>
More info at the Log4net reference.

Related

Retrieve MDC values in logback

I am trying to log the MDC values in stdout and in logstash.
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-5level [%thread] %logger{0}: %msg -someName=%X{mdcFieldKey} %n</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<appender name="logstash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>kibanaurl:port</destination>
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<customFields>
{
"application-name":"${spring.application.name}",
"someName":"${mdcFieldKey}",
"dummyName":"dummyValue"
}
</customFields>
<provider class="net.logstash.logback.composite.loggingevent.ArgumentsJsonProvider"/>
</encoder>
</appender>
Java code:
MDC.put("mdcFieldKey", "value to be displayed in kibana");
The STDOUT appender is displaying the mdc value correctly on kibana but for the logstash appender I see someName_IS_UNDEFINED. The hardcoded dummyname is also displayed correctly.
Why is the mdc value not populated in logstash custom field?
check here https://github.com/logstash/logstash-logback-encoder#mdc-fields
Add the line <includeMdcKeyName>mdcFieldKey</includeMdcKeyName> as below is one option. The field name will be same as mdc key in this case
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-5level [%thread] %logger{0}: %msg -someName=%X{mdcFieldKey} %n</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<appender name="logstash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>kibanaurl:port</destination>
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<includeMdcKeyName>mdcFieldKey</includeMdcKeyName>
<customFields>
{
"application-name":"${spring.application.name}",
"dummyName":"dummyValue"
}
</customFields>
<provider class="net.logstash.logback.composite.loggingevent.ArgumentsJsonProvider"/>
</encoder>
</appender>

RootLogger to output different levels to different files

I want to have log4j output INFO level to info.log and DEBUG level to debug.log, so that with this piece of code:
logger.info("This is an info message");
logger.debug("This is a debug message");
only the first would go to info.log, while both would go to debug.log.
This doesn't work:
log4j.rootLogger=INFO, R, T
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%r %-5p %c %x - %m%n
log4j.appender.R=org.apache.log4j.FileAppender
log4j.appender.R.File=info.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
log4j.appender.R.Threshold = INFO
log4j.appender.T=org.apache.log4j.FileAppender
log4j.appender.T.File=debug.log
log4j.appender.T.layout=org.apache.log4j.PatternLayout
log4j.appender.T.layout.ConversionPattern=%p %t %c - %m%n
log4j.appender.T.Threshold = DEBUG
Neither does this:
log4j.rootLogger=INFO, R
log4j.rootLogger=DEBUG, T
log4j.appender.R=org.apache.log4j.FileAppender
log4j.appender.R.File=info.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
log4j.appender.R.Threshold = INFO
log4j.appender.T=org.apache.log4j.FileAppender
log4j.appender.T.File=debug.log
log4j.appender.T.layout=org.apache.log4j.PatternLayout
log4j.appender.T.layout.ConversionPattern=%p %t %c - %m%n
log4j.appender.T.Threshold = DEBUG
You can use a filter, org.apache.log4j.varia.LevelMatchFilter. e.g.:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN"
"log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- INFO appender -->
<appender name="INFOFILE" class="org.apache.log4j.FileAppender">
<param name="file" value="info.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="conversionPattern"
value="%d{yyyyMMdd-HHmmss.SSS} %-5p (%c.java:%L).%M - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelMatchFilter">
<param name="levelToMatch" value="INFO" />
</filter>
</appender>
<!-- DEBUG appender -->
<appender name="DEBUGFILE" class="org.apache.log4j.FileAppender">
<param name="file" value="debug.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="conversionPattern"
value="%d{yyyyMMdd-HHmmss.SSS} %-5p (%c.java:%L).%M - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelMatchFilter">
<param name="levelToMatch" value="DEBUG" />
</filter>
</appender>
<!-- root -->
<root>
<priority value="ALL" />
<appender-ref ref="INFOFILE" />
<appender-ref ref="DEBUGFILE" />
</root>
</log4j:configuration>
Put all this in one file in the default package: log4j.xml.

getAppender return null from xml

when I try to read a appender from XML I get return null,
This is my file. xml
<appender name="FileInfoStatistics" class="utils.monitorstatistics.CustonAppenderRollFile">
<param name="file" value="Statistics.log"/>
<param name="MaxFileSize" value="100KB"/>
<layout class="utils.monitorstatistics.CustomAppenderStatistics">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<logger name="utils.monitorstatistics" additivity="false">
<level value="INFO"/>
<appender-ref ref="FileInfoStatistics"/>
</logger>
and this is the part java where I try to read the appender:
Logger mylogger = Logger.getLogger("utils.monitorstatistics");
Appender app = mylogger.getAppender("FileInfoStatistics");
getAppender return null

configure log4j file

I have this log4j.config
<appender name="FileInfoStatistics" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="${log.dir}/T_Statistics.log" />
<param name="MaxFileSize" value="8000KB"/>
<!-- Keep one backup file -->
<param name="MaxBackupIndex" value="1"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %5p %c{1} - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="INFO" />
</filter>
</appender>
but I would like just when then file T_Statistics.log is created firt time and one line as e.g This a log file, Is this possible from log4j.config?
I saw this is possible en log4net with:
<param name="Header" value="xxxx"
Is there something like in log4j?
Well, After some research I found a solution to my problem, said if someone would be useful.
I have created a custom appender:
package com.mycompany.logger;
import org.apache.log4j.PatternLayout;
public class MyPatterLayout extends PatternLayout
{
#Override
public String getHeader()
{
return "message id, file name, start time, end time, status" + System.getProperty("line.separator");
}
}
And then I have configured my log4j.xml:
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="com.mycompany.logger.MyPatterLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
And this is the result:
message id, file name, start time, end time, status
DEBUG App - Here is some DEBUG
INFO App - Here is some INFO
WARN App - Here is some WARN
ERROR App - Here is some ERROR
FATAL App - Here is some FATAL

Log4Net Rolling File Appender Rolling issue

I have the following log4net config:
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="Logs/%date{yyyy-MM-dd} Service.log" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<rollingStyle value="Date"/>
<datePattern value="yyyy-MM-dd"/>
<maxSizeRollBackups value="100"/>
<maximumFileSize value="15MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger: %message%newline" />
</layout>
</appender>
Data will be logged constantly to the log file and rolls OK but I end up having rolled files like this:
2009-12-21 Service.log2009-12-22 (this is what it will write tonight)
2009-12-21 Service.log <-- this being the latest file
2009-12-21 Service.log2009-12-21 <-- last updated 23:59
I want the files to be like:
2009-12-21 Service.log
2009-12-22 Service.log
2009-12-23 Service.log
Get rid of the file name and the type in the file element:
<file value="Logs\" />
Then change your datePattern to (note: make sure you escape the letters in 'Service' appropriately, like the g in 'log' is a special format, so you need to escape it with the '\'):
<datePattern value="yyyy-MM-dd Service.lo\g"/>
I think the following should be what you need.
Add in the following element within your <appender />.
<staticLogFileName value="true" />
You can use the function below.
In this function first get file location that you set in webconfig and after that you can add any path that you want! (like Date, our Customer, or...)
WebConfig:
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\\t4\\"/>
<appendToFile value="true"/>
<rollingStyle value="Composite"/>
<datePattern value="_yyyy-MM-dd.lo'g'"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="1MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date User:%identity IP:%X{addr} Browser: %X{browser} Url: %X{url} [%thread] %-5level %c:%m%n"/>
</layout>
</appender>
Function:
public static void ChangeFileLocation(string _CustomerName,string _Project)
{
XmlConfigurator.Configure();
log4net.Repository.Hierarchy.Hierarchy h = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();
foreach (IAppender a in h.Root.Appenders)
{
if (a is FileAppender)
{
FileAppender fa = (FileAppender)a;
string sNowDate= DateTime.Now.ToLongDateString();
// Programmatically set this to the desired location here
string FileLocationinWebConfig = fa.File;
string logFileLocation = FileLocationinWebConfig + _Project + "\\" + _CustomerName + "\\" + sNowDate + ".log";
fa.File = logFileLocation;
fa.ActivateOptions();
break;
}
}
}
and result like this: C:\Logs\TestProject\Customer1\Saturday, August 31, 2013.log

Resources