log4net log file is created but always empty
There is probably a problem in your configuration, enable internal debug to see what it is:
<configuration>
...
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
Log4net FAQ
Python logging creates empty log file
I found the problem ! I didn't realize but when defining handlers
in the log.conf
file, the order of the handlers and formatters is important !
I changed the log.conf
changed to:
[loggers]
keys=root,sLogger
[handlers]
keys=consoleHandler,fileHandler
[formatters]
keys=consoleFormatter, fileFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler, fileHandler
[logger_sLogger]
level=DEBUG
handlers=consoleHandler, fileHandler
qualname=sLogger
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=WARNING
formatter=consoleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=WARNING
formatter=fileFormatter
args=('%(logfilename)s','a')
[formatter_fileFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
[formatter_consoleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
NOTE the changed order between consoleFormatter
and fileHandler
in the [formatters]
section.
The rest is working perfectly fine.
To make it easier to play around with I put it in a function (which is probably redundant I suppose):
def base_logger(path_conf, fname, savedir):
'''
Base logging function to be started once
in the main script then used in every other
modules.
Args:
- path_conf: str, path to the configuration
file {log.conf}
- fname: str, name of the saved log file
- savedir: str, path of the saving directory
Returns:
- logging object to be used in the other scripts
Example:
In main.py:
main():
base_logger(paht_cong = './log.conf', fname='file', savedir='project)
In module.py:
# AFTER all the import
logger = logging.getLogger(__name__) # To ge the module name reported in the log file
...
logger.error(f'Error message regarding variable {var}')
The logger initialization {logger = logging.getLogger(__name__)},
has to be done in every file that will use logging !
'''
logging.config.fileConfig(fname=path_conf,
defaults={'logfilename': os.path.join(savedir, f'{fname}.log')},
disable_existing_loggers=False)
I would add that the logger = logging.getLogger(__name__)
has to be placed after all imports
to make sure that the module
name displayed in the log is not imported from other modules.
Logback log file empty
Probably you missed the logback-core dependency.
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.10</version>
</dependency>
or
dependencies {
...
implementation 'ch.qos.logback:logback-core:1.2.10'
...
}
In addition to the other two you already have.
Other thing to do is to update to the latest versions of each dependency and see if the problem still occurs.
Reference: https://sematext.com/blog/logback-tutorial/ or https://www.baeldung.com/logback
log4j2 creates empty logs file
I case someone has this same problem, I've just solved it.
The problem was the way I was loading the xml config; I've changed it like this:
LoggerContext ctx = getLoggerContext();
ConfigurationSource configurationSource = new ConfigurationSource(new FileInputStream(new File(log4Jcfg)));
ctx.start(ConfigurationFactory.getInstance().getConfiguration(ctx, configurationSource));
and now it works perfect!
Log file gets created but remains empty?
You don't need the CheckFile()
method. AppendText()
will create the file if necessary.
The real problem is how you're writing the file. Change your method to this:
public static string Log(string code, string message)
{
string log;
using (var writer = File.AppendText(FilePath))
{
log = ("\r\n" + code + ": \n");
log += String.Format("{0} {1}\n", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
log += String.Format(" :{0}\n", message);
log += String.Format("-------------------------------");
writer.WriteLine(log);
}
return log;
}
To clarify, the using
block calls Dispose()
on the StreamWriter
. This flushes content to the file.
Generating empty log files with Log4J2
So, I have managed to output the logs to the file and to the console:
appender.file.type = File
appender.file.name = file
appender.file.fileName=target/myLog.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n
appender.out.type = Console
appender.out.name = out
appender.out.layout.type = PatternLayout
appender.out.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
rootLogger.level = all
rootLogger.appenderRef.file.ref = file
rootLogger.appenderRef.file.ref = out
Related Topics
Converting Exponential Value in Java to a Number Format
How to Resolve Java.Lang.Noclassdeffounderror: Javax/Xml/Bind/Jaxbexception
Parse Xml to Java Pojo in Efficient Way
The Import Org.Junit Cannot Be Resolved
How to Create Comma Separated String in Single Quotes from Arraylist of String in Java
Adb Cannot Connect to Daemon At Tcp:5037
How to Refresh or Reload the Jframe
Split Comma Separated Values in Java, Int and String
Password Validate 8 Digits, Contains Upper, Lowercase, and a Special Character
Javax.Net.Ssl.Sslexception: Certificate Doesn't Match Any of the Subject Alternative Names
Java H2 In-Memory Database Error: Table Not Found
Validate an Enum With Springframework Validation Errors
Getting Data from Incoming Json in a Java Servlet
Broadcast Receiver Is Not Working When Application Is Removed from Background
Classcastexception: Java.Math.Biginteger Cannot Be Cast to Java.Lang.Long on Connect to MySQL
Automatically Size Jpanel Inside Jframe
Testing Two Json Objects for Equality Ignoring Child Order in Java