81

I use Spring Boot and want it to write log output to a file.

According to the docs, this is simply done by setting

logging.file=filename.log

While the console output works fine, filename.log is not created. Also, if I create the file manually, nothing is written to it. What do I miss?

8
  • 1
    Where did you put your filename.log? Commented Jul 22, 2016 at 13:06
  • Please show your : application.properties file Commented Jul 22, 2016 at 13:28
  • By default, Spring Boot configures logging via Logback (logback.qos.ch) to log to the console at INFO level. However, if you decide that you’d rather use Log4j or Log4j2, you’ll need to change your dependencies to include the appropriate starter for the logging implementation you want to use and to exclude Logback. Commented Jul 22, 2016 at 13:33
  • @AliDehghani I assumed the logfile will be created if it does not exist. However, I created the file manually in the directory where I start the application, but nothing is written to it. I also used logging.path=/var/log as in the docs, but no log file is created there either. Commented Jul 26, 2016 at 7:07
  • 10
    Use logging.file.name for 2.2+ instead. logging.file was deprecated in 2.2 and totally removed in 2.3, so you can no longer use logging.file in 2.3+.
    – barryku
    Commented May 31, 2020 at 21:51

25 Answers 25

97

Use logging.file.name instead of logging.file

In higher versions of spring-boot-parent(from version 2.2.0), property logging.file is deprecated.

3
  • 2
    I have upgraded to the latest Springboot version and the log file was not created. Thanks for the answer.
    – nandeesh
    Commented Jul 15, 2020 at 13:51
  • 1
    It worked for me. I am using 2.3.1 version. Thanks a lot. It was really helpful.
    – Goose
    Commented Jul 24, 2020 at 3:14
  • 2
    link to documentation (choose your Spring Boot version): docs.spring.io/spring-boot/docs Commented Aug 30, 2021 at 9:55
33

I found a solution. I am not very happy with it since it still does not answer my original question why the logging.file property is not respected.

I created the logback-spring.xml from Georges' answer in the same directory where application.properties resides. According to the documentation Spring Boot will pick it up from there. Apparently, this does not happen in my case.

I need to additionally add logging.config=classpath:logback-spring.xml in order it is picked up by Spring. The relevant parts of my application.properties are now

logging.config=classpath:logback-spring.xml
logging.file=logs/logfile.log

(I created the logs directory manually.)

5
  • +1 : logging.config is needed in application.properties if somebody is trying to integrate spring batch admin UI with a Spring Boot batch job and have overridden env-context.xml from spring-batch-admin-manager project.
    – Sabir Khan
    Commented Mar 8, 2017 at 12:12
  • Has your project already included logback.xml in the resource folder? Commented May 24, 2017 at 1:35
  • logging.file is respected for sure, depends on the fact how you specify the path, file will be created there. As a sample, in my project I have following configuration of logging in the application.yml - logging: file: logs/dictoro-livescore-api.log level: INFO and it is creating log file in file system (I'm using Linux Ubuntu) in the folder /logs Commented Feb 19, 2018 at 7:22
  • This is not necessary: logging.config=classpath:logback-spring.xml. But it might be useful if you want to have different logback configs for different profiles (prod vs dev). Also you don't have to create the folder.
    – ACV
    Commented Jan 19, 2021 at 23:07
  • How do I create log files inside my spring boot project directory? I want to create separate files for error and info messages. I'm using spring boot v. 2.5 Thanks in advance.
    – Waseem
    Commented Sep 14, 2021 at 11:34
25

In my case, I used below, in the application property file.

logging.file

Instead, I need to use the below one:

logging.file.name

Since then, I could be able to get the logs into the directed path file.

0
11

I had the same problem. It's more than likely due to file permissions on the file system. I had the application folder owned by root, but ./logs owned by the process owner. As such, the following didn't work:

logging.file=my.log

but this did

logging.file=/opt/myapp/logs/my.log
1
  • As indicated by Vivek below, logging.file is now deprecated so unless you're using an older version of Spring, please follow that guidance instead of mine which is now out of date.
    – beaudet
    Commented Dec 21, 2021 at 18:10
8

Spring Boot: Version 2.4.3

Either one of them should be used in application.properties file: logging.file.name or logging.file.path

For example:

logging.file.name=logs/myapp.log
logging.file.path=logs

You don't have to create logs directory. It will be created automatically in class path.

To see other deprecated properties, read this class file ~/.m2/repository/org/springframework/boot/spring-boot/2.4.3/spring-boot-2.4.3.jar!/org/springframework/boot/logging/LoggingSystemProperties.class

1
  • did not work for me logging.file.path=../tmp
    – likejudo
    Commented Mar 23, 2023 at 16:09
6

Here is how i managed to write output to a local file file. To disable console logging and write output only to a file you need a custom logback-spring.xml ( call it logback-spring.xml so you ll take advantage of the templating features (date formatting etc..) provided by Boot) that imports file-appender.xml instead of console-appender.xml. In order to achieve this, you must paste this code below into your logback-spring.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration> 

You also need to add the following to your application.properties:

logging.file=myapplication.log

Notice that this log file myapplication.log will be generated by springboot.

This is how my application structure tree looks like:

enter image description here

If you want to have more fun, you can locate the base.xml in your maven dependencies like this:

enter image description here

4
  • 1
    Sorry, but this does not do the trick for me, either. I changed my application.properties such that the only logging-related line is logging.file=logfile.log. This disables console logging. Yet, no logfile is written. (Yes, I'm using Spring Boot 1.3.6 and Yes, the logback config file resides under resources). Commented Jul 28, 2016 at 14:59
  • did you refresh your app after running it ? Commented Jul 28, 2016 at 15:04
  • you can download my code and test it. : drive.google.com/file/d/0B_EVyl90ivXwQ3NpVHllVWpQZmM/… Commented Jul 28, 2016 at 15:10
  • See my answer below: logging.config=classpath:logback-spring.xml did the trick. Commented Jul 29, 2016 at 8:55
5

I don't know whether this would help you but I am also using Logback in my Spring-Boot project and the structure is as below

enter image description here

File: logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="logback.xsd">

    <property resource="\application.properties"/>

    <appender name="FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${app.logPathPrefix}/myproject.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${app.logPathPrefix}/myproject.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>50MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>30</maxHistory>
        </rollingPolicy>

        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [%thread] [%logger:%line] %msg%n
            </pattern>
        </encoder>
    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [%thread] [%logger:%line] %msg%n
            </pattern>
        </encoder>
    </appender>


    <logger name="org.springframework" level="INFO" />
    <logger name="com.mycompany" level="INFO" />
    <logger name="org.hibernate" level="DEBUG" />


    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>

</configuration>

File: application.properties

app.logPathPrefix=/var/log/myproject
5

Check the version of the Springboot parent.

if it is 2.3.x+ then the property should be logging.file.name=yourapplog.log

3

If you are using Maven add the dependency :

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.6</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
</dependency>

Now you have to specify a file that is called 'log4j.properties' which you have to put in the specific directory : ' src/main/resources/log4j.properties '

Here is how the file should look for example :

# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.logger.org.springframework.ws.client.MessageTracing.sent=TRACE
log4j.logger.org.springframework.ws.client.MessageTracing.received=TRACE

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# log4j.appender.springlog.Threshold=INFO
log4j.appender.springlog.layout=org.apache.log4j.PatternLayout
log4j.appender.springlog.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:/example/filename.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Now import these :

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Declare a logger variable like this :

final static Logger logger = Logger.getLogger(TheClassYourIn.class);

And use it in the class like this :

logger.info("Well hello world then ");

This way it works for me. I hope that this answer will help you . Good luck !

PS: log4j.appender.file.File='directory' is how you specify where the logs to be stored. If you don't specify a directory and just leave it as filename.log this file will be automaticly created in the project dir.

2
  • This is a valid answer in my opinion. Sometimes the answer may not work because of the user environment or the package the the user suppose to log isn't specified. I am giving a up vote for this. Commented Jul 22, 2016 at 19:07
  • Thank you for the detailed example. However, I will use logback since it comes with Spring Boot. Commented Jul 25, 2016 at 6:29
3

If you want to place log file in specific directory like D drive then below changes can be done in spring boot project

1.Create logback-spring.xml configuration file and mention the package name of which you want to create logs

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    
        <logger name="com.example.demo" 
        level="DEBUG" >
           
        </logger>
</configuration>

2.Also make below addition in application.properties file

logging.config=classpath:logback-spring.xml
logging.file.name=F:/Springbootlogs/filename.log

Note: The mentioned changes are for version 2.4.3

1

I just used the Spring-boot provided logging mechanism. I wrote below in my 'logback.xml' file :

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/file- appender.xml" />
<root level="INFO">
<appender-ref ref="FILE" />
</root>
</configuration>

I put the both application.properties and logback.xml file under same package 'src/main/resources'. In application.properties file just added one parameter :

logging.file = xyz.log

It worked perfectly fine for me.

1
  • There is a typo in the include of the file-appender.xml, but I cannot edit it because it's less than 6 characters
    – Alecz
    Commented Jan 31, 2019 at 21:48
1

In my case, I added a file "logback.xml" in one of my sub module by mistake which caused this issue, remove it and everything will be fine.

1

Sorry for the late reply. It seems spring's logger reads the property from its own classpath.Due to precedence, it's not respecting the properties supplied.

Some tricks to get around:

  1. In main class set the property variable using springApplication.setDefaultProperties(properties); like this
public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(MainClass.class);
        Properties properties = new Properties();
        properties.put("logging.file", logDirectory);
        springApplication.setDefaultProperties(properties);
        springApplication.run(args);
    }
  1. Pass the property as JVM parameter -Dlogging.file=/location/output.log.

Both of the above are not the best ones as in order to define other logging properties they also should follow the same way.

Solution

Define a property file and put all you logging configurations in that and specify the file in -Dspring.config.location. This is a derivation of my other problem and this is how I resolved that. check that out in order to know other solutions that I've tried and their challenges.

1

I also faced the same issue in windows operating system . I just changed -> logging.file to logging.file.name=D:/customer_projects/flight_reservation_system/logs/reservation.log

Note: Spring-boot version which i used is 2.4.1

in windows operating system when you copy file path from file explorer you will get file path like D:\customer_projects\flight_reservation_system\logs\flight_reservation.log

Above file path will not work. so you need to change file path like D:/customer_projects/flight_reservation_system/logs/reservation.log then it created a log file in our specified path. thank you.

1

Instead of the following in application.properties

logging.file = logFileName.log

use the below one

logging.file.name= appLogName.log

Check the Screenshot for your reference. enter image description here

1
logging.file.path=/home/log/
logging.file.name=/home/log/agricom.log

mention the path with filename in "logging.file.name". then it should work fine.

2
  • 2
    While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
    – Yunnosch
    Commented Feb 20, 2023 at 6:58
  • 1
    Is this answer really different from stackoverflow.com/a/66728794? Commented Feb 20, 2023 at 13:05
0

If you are on Spring Boot then you can directly add following properties in application.properties file to set logging level, customize logging pattern and to store logs in the external file.

These are different logging levels and its order from minimum << maximum.

OFF << FATAL << ERROR << WARN << INFO << DEBUG << TRACE << ALL

# To set logs level as per your need.
logging.level.org.springframework = debug
logging.level.tech.hardik = trace

# To store logs to external file
# Here use strictly forward "/" slash for both Windows, Linux or any other os, otherwise, your logs it won't work.      
logging.file=D:/spring_app_log_file.log

# To customize logging pattern.
logging.pattern.file= "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"

Please pass through this link to customize your logs more vividly.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

0

I was also facing same issues, since i just copied the path as windows(uses "\" in path) provide.

Fixed just by changing : back slash ("\") to forward slash ("/") in path.

Note: Strictly forward slash ("/") should be used in path, OS is not the constraint.

ex:- logging.file.name=D:/Logs/server.log

0

I run my spring boot service using command line argument which works fine. All the spring boot console log writes to the file. I don't have any logging configured in my application.properties file. Spring boot version: 2.0.5.RELEASE

In windows:

java -jar target\microservice-0.0.1.jar --logging.file=C:\\logs\\microservice.log

In Linux

java -jar target\microservice-0.0.1.jar --logging.file=\var\log\microservice.log
0

In my case I pasted some typical config and somehow most probably messed my logging pattern (logging.pattern.file)

Commenting it out solved my own issue (file was created, but nothing was written in it, even though there was console output and root logging level was set to DEBUG) - no errors were given otherwise.

[edit] In other case (I always seem to bump into this problem), I was referencing a JAR file with classes stripped from a web application (WAR), which contained a logback.xml, not to mention AppInitializer - I suspect AppInitializer wouldn't be a problem, since it has a completely different package name and shouldn't be scanned by Spring auto config.. but logback.xml was being detected, I guess, in the classpath, and messed everything completely. I knew it was a hack to reference a WAR, but I was hoping for a quick fix - fixing that, breaking something else. Mani's answer is related.

0

For Springboot 2.4.2, Below Application.yml configurations works :

logging:
    file:
        name: logpath
0

my problem was that the file is not getting created automatically, and even when i create it in the project root folder, it does not being written into, so eventually, i tried creating a folder and a file inside it logs/logfile.lo and setting logging.file.name=scripts/logfile.log and the application.proprieties file and it worked

0

I don't know why, but

logging.file.path=../tmp

does not work. It is ignored.

only this works

logging.file.name=../tmp/regular-encourager-quotes.log

Spring Boot starter is 2.7.5

Java 17

0

For application.yml below mentioned configurations worked for me:

    logging:
      file.name: logs/dev_app.log
0

On my macOS system, this setting below worked for me. myapp.log file was created in my project root directory.

logging.file.name = ./<logging-in-a-spring-boot-project-end>/myapp.log

<logging-in-a-spring-boot-project-end> given above represents the My Project path name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.