I use log4net and log4net.Async in my application to logs.It works good on my local environment(VS2017).When i release it and publish it to the IIS server,it works well at the starte time.But after i recycle the service,it can't write logs anymore,the log file is still there but has no log message inside.
I set the log folder whith permission(READ\WIRTE) for EVERYONE already.
there is my log config:
<appender name="InfoRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<param name="Encoding" value="utf-8" />
<param name="File" value="D:\Log\Info\" />
<param name="AppendToFile" value="true" />
<param name="rollingStyle" value="Date" />
<param name="datePattern" value="yyyyMMdd\\yyyy-MM-dd-HH.'Info.log'" />
<param name="staticLogFileName" value="false" />
<layout type="AsPay.GateWay.Log.AsRefundAccLayout">
<conversionPattern value="--logtime:%date --:%-5level--msg:%Logtxt --:%CallType%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
</filter>
</appender>
<appender name="asyncForwarder" type="Log4Net.Async.AsyncForwardingAppender,Log4Net.Async">
<appender-ref ref="InfoRollingFileAppender" />
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="asyncForwarder" />
</root>
code in Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
System.IO.FileInfo fileinfo = new System.IO.FileInfo(Server.MapPath("~/log4net.Config"));
log4net.Config.XmlConfigurator.Configure(fileinfo);
}
The strange thing is after recycle the IIS,the log file(eg:2019-04-10-00.Info.log) is continued to be created,but there is no log content in the logfile.After recycle the IIS, There are no problems with the functionality of the service,except the log.
Related
I cannot get log4net working on my ASP.NET project. My web.config looks like this:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net debug="true">
<appender name="console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline" />
</layout>
</appender>
<appender name="file" type="log4net.Appender.RollingFileAppender">
<file value="CardGame.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
</log4net>
And my LogHelper class looks this:
public class LogHelper
{
private static LogHelper _instance = new LogHelper();
private static volatile object _lock = new object();
public ILog Logger;
public static LogHelper Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new LogHelper();
}
}
return _instance;
}
}
private LogHelper()
{
Logger = LogManager.GetLogger(typeof(LogHelper));
Logger.Debug("Debug message");
Logger.Warn("Warn message");
Logger.Error("Error message");
Logger.Fatal("Fatal message");
}
}
I have also added the line
log4net.Config.XmlConfigurator.Configure();
to Application_Start in global.asax.cs
However none of the loggings in the constructor works and I am running out of ideas on why it does not work.
Make sure that the user running the app has write permissions on the target folder.
I always test that case by adding everyone and restarting the pool. If it works you know it's a permissions issue, otherwise check the code/config.
Which version are you using ? this is setting from my web.config
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="30" />
<maximumFileSize value="15MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<!--<conversionPattern value="%-5p %d %5rms [%thread] %-22.22c{1} %-18.18M - %m%n" />-->
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<!-- Options are "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" and "OFF". -->
<level value="ALL" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
I know that this question was asked many times but any answer solved my problem.
I am trying to implement a custom login form using Spring Security 4 + Hibernate + Spring Data Jpa, but things don't work as I expect.
When I use in-memory credentials all work fine but I want to use my database instead.
Below the main code :
Xml security config.
<beans:bean id="encodeurMotDePasse" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="12" />
</beans:bean>
<security:http auto-config="true" create-session="never">
<security:intercept-url pattern="/" access="permitAll" />
<security:intercept-url pattern="/inscription**" access="hasRole('ADMIN') or hasRole('USER')" />
<security:intercept-url pattern="/connexion**" access="hasRole('USER') or hasRole('USER')" />
<security:intercept-url pattern="/test**" access="hasRole('ADMIN')" />
<security:intercept-url pattern="/dba**" access="hasRole('ADMIN')" />
<security:form-login login-page="/login.html"
username-parameter="identifiant"
password-parameter="motDePasse"
authentication-failure-url="/login.html?error=t"/>
</security:http>
<beans:bean id="customUserDetailsService" class="com.app.security.CustomUserDetailsService"/>
<security:authentication-manager >
<security:authentication-provider user-service-ref ="customUserDetailsService">
<security:password-encoder ref="encodeurMotDePasse" />
</security:authentication-provider>
</security:authentication-manager>
The UserDetailsService implementation :
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private ServicesDAO service;
#Override
public UserDetails loadUserByUsername( String username ) throws UsernameNotFoundException {
T_authentification userPrincipals = service.getAuthenticatePrincipal( username );
if ( userPrincipals == null ) {
System.out.println( "user inexistant" );
throw new UsernameNotFoundException( "L'utilisateur n'a pas été trouvé" );
} else {
System.out.println( "user trouvé" );
}
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for ( T_roles role : userPrincipals.getRoles() ) {
System.out.println( " role dans userdetails service est :" + role.getRoleName() );
authorities.add( new SimpleGrantedAuthority( role.getRoleName() ) );
}
// return new CustomUserDetails( userPrincipals );
return new org.springframework.security.core.userdetails.User( userPrincipals.getUsername(), userPrincipals.getMotDePasse(), authorities );
}
}
When I test the code in a controller method all credentials are well loaded from the database and I can print them on the console.
The other concern is when the login fails, Spring Security doesn't send any debug message in the console to tell the cause of this failure.
EDIT
Here my log4j.xml, I follow the configuration but any message appears in the console and the file are also empty.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">
<appender name="Appender1" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-7p %d [%t] %c %x - %m%n"/>
</layout>
</appender>
<appender name="SpringAppender" class="org.apache.log4j.FileAppender">
<param name="file" value="C:/Log4j/Spring-details.log" />
<param name="Threshold" value="debug" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{MM/dd/yyyy HH:mm:ss} [%t]:%c{5}.%M()%L %m%n" />
</layout>
</appender>
<appender name="Appender2" class="org.apache.log4j.FileAppender">
<param name="File" value="C:/Log4j/app.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-7p %d [%t] %c %x - %m%n"/>
</layout>
</appender>
<category name="org.springframework">
<priority value="ALL" />
</category>
<category name="org.springframework">
<priority value="debug" />
</category>
<category name="org.springframework.beans">
<priority value="debug" />
</category>
<category name="org.springframework.security">
<priority value="debug" />
</category>
<category
name="org.springframework.beans.CachedIntrospectionResults">
<priority value="debug" />
</category>
<category name="org.springframework.jdbc.core">
<priority value="debug" />
</category>
<category name="org.springframework.transaction.support.TransactionSynchronizationManager">
<priority value="debug" />
</category>
<logger name="org.springframework" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="SpringAppender"/>
</logger>
<root>
<!-- <priority value="INFO"/> -->
<level value="DEBUG"/>
<appender-ref ref="Appender1" />
<appender-ref ref="SpringAppender" />
<appender-ref ref="Appender2" />
</root>
</log4j:configuration>
EDIT2
I got this exception when I try to #Autowire this bean <beans:bean id="customUserDetailsService" class="com.app.security.CustomUserDetailsService"/> in a java class.
Why this error occured?
ERROR javax.enterprise.web.core - ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inscriptionController': Unsatisfied dependency expressed through field 'customUserDetailsService'; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'customUserDetailsService' is expected to be of type 'com.app.security.CustomUserDetailsService' but was actually of type 'com.sun.proxy.$Proxy323'
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5985)
Many thanks for your clarifications and sorry for my bad English.
I found the reason of this strange behavior.
I suppose that the spring security listener org.springframework.security.web.session.HttpSessionEventPublisherdoesn't share the same context as the servlet dispatcher. So, all beans defined in the mvc context are inaccessible for the security part.
To solve this, I had to add the <context:component-scan base-package=.... in the root context as all beans defined here are accessible everywhere.
I lost 2 weeks to find the reason of my problem :( !
hy guys,
is there a best practice of how to get flyway output into log4j logs?
I'm currently running with following log4j.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
<appender name="CA" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-p - %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="INFO"/>
<param name="levelMax" value="ERROR"/>
</filter>
</appender>
<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
<param name="append" value="false"/>
<param name="file" value="log.out"/>
<param name="immediateFlush" value="true"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n"/>
</layout>
</appender>
<logger name="com.googlecode.flyway.core.migration" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="fileAppender"/>
</logger>
<root>
<priority value="all"/>
<appender-ref ref="CA"/>
<appender-ref ref="fileAppender"/>
</root>
</log4j:configuration>
I have already searched for an answer online but could not figure it out.
Flyway will automatically use Log4J if it is available on the classpath.
Probably a very simple setup, but I've tried to setup Log4Net. In my web.config I have:
<log4net>
<appender name="File" type="log4net.Appender.RollingFileAppender">
<file value="Logs\\Log4Net.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd-HHmm" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<logger name="File">
<level value="All" />
<appender-ref ref="LogFileAppender" />
</logger>
<root>
<level value="ALL"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
I have added the following to my configsections:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
The following in global.asax:
log4net.Config.XmlConfigurator.Configure();
The following is on my default.aspx:
ILog alog = log4net.LogManager.GetLogger(typeof(_Default));
log4net.ILog logger = log4net.LogManager.GetLogger("File");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetupSeo();
}
alog.Error("this test");
logger.Error("Front page loaded for ip " + Request.UserHostAddress);
}
What is wrong?
I guess it is a Permission issue. The relevant directory do not have sufficent permissions so that ASP.NET can write to that.
To verify that, Enable log4net internal debugging by adding the below item to the <appSettings> section in the webconfig.
<add key="log4net.Internal.Debug" value="true"/>
Now add the below to the webconfig as well
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\myLogFolder\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
Make sure that myLogFolder folder in C drive have permissions so that ASP.NET can write to that. This will write the internal debugging message to this file. Run the app and see what happens.
I use log4net to log the errors in my web application and it works fine. However if I place the same code in website I get error "Unrecognized configuration section log4net"
here is my web.config section
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" requirePermission="false"/>
<root>
<level value="RELEASE" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value="D:\ESSReport\Logs\ESSlog.log" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="4MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%newline%-5p%d{yyyy-MM-dd hh:mm:ss} [%thread] [%logger] [%line] %newline - %message" />
</layout>
</appender>
I have added dll to my website
You are probably missing configuration section registration.
Here is sample code how you can register custom section:
<configuration>
<configSections>
<sectionGroup name="LoggerConfiguration">
<section name="GPWFLogger" type="GP.Solutions.WF.Entities.LoggerConfiguration,GPWFLogger" allowDefinition="Everywhere" allowLocation="true"/>
</sectionGroup>
</configSections>
<LoggerConfiguration>
<GPWFLogger
ConnectionStringName="ASPNETDB"
LogLevel="Full"
LogPrimaryTarget="SqlServer"
LogFilePath="GPWFwebClient.log" />
</LoggerConfiguration>
Take notice that LoggerConfiguration is registred inside sectionGroup.
You can use this principle in your case.