Context
Responding to the:
I read the answer to similar questions but nobody actually says how to fix the problem.
part of the question for gradle
(instead of Maven).
Instructions
To log towards a file at the root of your project named: my-log-file.log
, using:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
...
LOGGER.info("This is an info message");
LOGGER.error("This is an error message");
The following 2 steps can be used:
1. Add the dependencies for outputting a log file to build.gradle
In build.gradle
add:
dependencies {
// Allow logging to file.
implementation 'org.slf4j:slf4j-api:1.7.32'
implementation 'ch.qos.logback:logback-classic:1.2.6'
}
2. Create the logging output configuration file
Create a file named: logback.xml
and store it, as said the above answer, in:
src/main/resources
(not in src/main/resources/com/<projectname>/
). And it should contain:
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>my-log-file.log</file> <!-- Specify the file name here -->
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="FILE"/>
</root>
</configuration>
That is it, if you now build and run your java program, you should see a file named: my-log-file.log
at the root of your repository/project, with content:
2023-10-28 20:41:55,394 INFO [main] c.d.Main [Main.java:36] - This is an info message
2023-10-28 20:41:55,394 ERROR [main] c.d.Main [Main.java:37] - This is an error message
Assumptions
This question assumes you already have a working org.slf4j.Logger
setup that shows logging info in the terminal but does not store it to file.