将控制台输出路由到 Springboot 中的日志文件
我正在尝试将控制台日志记录路由到文件。虽然我能够生成日志文件,但它没有捕获从 logger.info 生成的输出。输出打印在控制台上,但没有反映在日志文件中。
application.properties:
logging.file.path= log
logging.pattern.file= [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
代码:
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Service
public class GetImageFiles {
@Value("${app.images.base.url}")
String imagesBaseUrl;
@Autowired
DataAccessor dataAccessor;
private static Logger logger = LoggerFactory.getLogger(GetImageFiles.class);
public void getImageDetails(String sessionID, String imageId, String articleId){
HashMap<String, String> map = new HashMap<>();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-Chorus-Session",sessionID);
HttpEntity<String> request = new HttpEntity<>(null, headers);
String imageFilesUrl = imagesBaseUrl + "/" + imageId;
ResponseEntity<String> responseEntity = restTemplate.exchange(imageFilesUrl, HttpMethod.GET, request, String.class);
JSONObject jsonObject = new JSONObject(responseEntity.getBody());
String imageName = jsonObject.get("filename").toString();
JSONObject thumbnails = (JSONObject) jsonObject.get("thumbnails");
JSONObject thumbnailsSize = (JSONObject) thumbnails.get("large");
String imageUrl = thumbnailsSize.get("url").toString();
map.put(imageName, imageUrl);
for(Map.Entry<String, String > mapValue : map.entrySet()) {
if (mapValue.getKey().lastIndexOf(".") > 0) {
String imageMapKey = mapValue.getKey().substring(0, mapValue.getKey().lastIndexOf("."));
if (imageMapKey.equals(articleId)) {
logger.info("Processing : The image name is : " + mapValue.getKey() + " and the imager URL is :" + mapValue.getValue() + " for article Id is :" + articleId);
dataAccessor.updateImageDetails(mapValue.getKey(), mapValue.getValue(), articleId);
}
}
}
}
}
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
控制台输出..
2022-03-09 17:17:00.110 INFO 32900 --- [ restartedMain] o.s.b.w.e.t.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-03-09 17:17:00.122 INFO 32900 --- [ restartedMain] c.a.t.ThirdlightApplication : Started ThirdlightApplication in 11.293 seconds (JVM running for 12.775)
Total Article Ids to be processed :10
There is no image ids to be processed for article id :52KTM41
There is no image ids to be processed for article id :52LGY10
There is no image ids to be processed for article id :52NAZ41
There is no image ids to be processed for article id :52NBT60
There is no image ids to be processed for article id :52NEK40
There is no image ids to be processed for article id :52QAZ30
There is no image ids to be processed for article id :54LAQ01
There is no image ids to be processed for article id :54LAQ20
There is no image ids to be processed for article id :56NAK43
There is no image ids to be processed for article id :56NEU40
The process has been completed !
spring.log:
[INFO ] 2022-03-09 17:20:49.920 [restartedMain] ThirdlightApplication - Starting ThirdlightApplication using Java 11.0.7 on LHTU05CD9032TMM with PID 6456 (C:\Users\psingh69\Downloads\thirdlight\target\classes started by psingh69 in C:\Users\psingh69\Downloads\thirdlight)
[INFO ] 2022-03-09 17:20:49.933 [restartedMain] ThirdlightApplication - No active profile set, falling back to 1 default profile: "default"
[INFO ] 2022-03-09 17:20:50.000 [restartedMain] DevToolsPropertyDefaultsPostProcessor - Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
[INFO ] 2022-03-09 17:20:50.000 [restartedMain] DevToolsPropertyDefaultsPostProcessor - For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
[INFO ] 2022-03-09 17:20:59.846 [restartedMain] TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
[INFO ] 2022-03-09 17:20:59.994 [restartedMain] ServletWebServerApplicationContext - Root WebApplicationContext: initialization completed in 9993 ms
[INFO ] 2022-03-09 17:21:00.670 [restartedMain] OptionalLiveReloadServer - LiveReload server is running on port 35729
[INFO ] 2022-03-09 17:21:00.723 [restartedMain] TomcatWebServer - Tomcat started on port(s): 8080 (http) with context path ''
[INFO ] 2022-03-09 17:21:00.742 [restartedMain] ThirdlightApplication - Started ThirdlightApplication in 11.588 seconds (JVM running for 13.107)
I am trying to route the console logging to a file. Though, I was able to generate the log file but it's not capturing the output generated from logger.info . The output is getting printed on the console but the same is not reflecting in the log file.
application.properties :
logging.file.path= log
logging.pattern.file= [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
Code :
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Service
public class GetImageFiles {
@Value("${app.images.base.url}")
String imagesBaseUrl;
@Autowired
DataAccessor dataAccessor;
private static Logger logger = LoggerFactory.getLogger(GetImageFiles.class);
public void getImageDetails(String sessionID, String imageId, String articleId){
HashMap<String, String> map = new HashMap<>();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-Chorus-Session",sessionID);
HttpEntity<String> request = new HttpEntity<>(null, headers);
String imageFilesUrl = imagesBaseUrl + "/" + imageId;
ResponseEntity<String> responseEntity = restTemplate.exchange(imageFilesUrl, HttpMethod.GET, request, String.class);
JSONObject jsonObject = new JSONObject(responseEntity.getBody());
String imageName = jsonObject.get("filename").toString();
JSONObject thumbnails = (JSONObject) jsonObject.get("thumbnails");
JSONObject thumbnailsSize = (JSONObject) thumbnails.get("large");
String imageUrl = thumbnailsSize.get("url").toString();
map.put(imageName, imageUrl);
for(Map.Entry<String, String > mapValue : map.entrySet()) {
if (mapValue.getKey().lastIndexOf(".") > 0) {
String imageMapKey = mapValue.getKey().substring(0, mapValue.getKey().lastIndexOf("."));
if (imageMapKey.equals(articleId)) {
logger.info("Processing : The image name is : " + mapValue.getKey() + " and the imager URL is :" + mapValue.getValue() + " for article Id is :" + articleId);
dataAccessor.updateImageDetails(mapValue.getKey(), mapValue.getValue(), articleId);
}
}
}
}
}
pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
Console output ..
2022-03-09 17:17:00.110 INFO 32900 --- [ restartedMain] o.s.b.w.e.t.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-03-09 17:17:00.122 INFO 32900 --- [ restartedMain] c.a.t.ThirdlightApplication : Started ThirdlightApplication in 11.293 seconds (JVM running for 12.775)
Total Article Ids to be processed :10
There is no image ids to be processed for article id :52KTM41
There is no image ids to be processed for article id :52LGY10
There is no image ids to be processed for article id :52NAZ41
There is no image ids to be processed for article id :52NBT60
There is no image ids to be processed for article id :52NEK40
There is no image ids to be processed for article id :52QAZ30
There is no image ids to be processed for article id :54LAQ01
There is no image ids to be processed for article id :54LAQ20
There is no image ids to be processed for article id :56NAK43
There is no image ids to be processed for article id :56NEU40
The process has been completed !
spring.log :
[INFO ] 2022-03-09 17:20:49.920 [restartedMain] ThirdlightApplication - Starting ThirdlightApplication using Java 11.0.7 on LHTU05CD9032TMM with PID 6456 (C:\Users\psingh69\Downloads\thirdlight\target\classes started by psingh69 in C:\Users\psingh69\Downloads\thirdlight)
[INFO ] 2022-03-09 17:20:49.933 [restartedMain] ThirdlightApplication - No active profile set, falling back to 1 default profile: "default"
[INFO ] 2022-03-09 17:20:50.000 [restartedMain] DevToolsPropertyDefaultsPostProcessor - Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
[INFO ] 2022-03-09 17:20:50.000 [restartedMain] DevToolsPropertyDefaultsPostProcessor - For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
[INFO ] 2022-03-09 17:20:59.846 [restartedMain] TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
[INFO ] 2022-03-09 17:20:59.994 [restartedMain] ServletWebServerApplicationContext - Root WebApplicationContext: initialization completed in 9993 ms
[INFO ] 2022-03-09 17:21:00.670 [restartedMain] OptionalLiveReloadServer - LiveReload server is running on port 35729
[INFO ] 2022-03-09 17:21:00.723 [restartedMain] TomcatWebServer - Tomcat started on port(s): 8080 (http) with context path ''
[INFO ] 2022-03-09 17:21:00.742 [restartedMain] ThirdlightApplication - Started ThirdlightApplication in 11.588 seconds (JVM running for 13.107)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就我而言,我必须将配置文件“logback.xml”放在文件夹 src/main/resources 中...
它是高度可定制的,但您可以从这样的东西开始(STDOUT - 控制台 - 和文件同时写入):
上面的示例在“/logs”文件夹中写入“yourappname.log”文件(如果您使用的是 Windows 并且您的应用程序运行在驱动器 C: 上,则为 C:\logs\yourappname.log) /logs/yourappname.log(如果您使用的是 Linux 或 MacOS)。
此外,上述配置文件提供了一种基于时间的 LogRotation 机制(这意味着,按照固定的时间间隔(本例中为 7 天),日志文件会以 tar.gz 的方式进行压缩和归档,并重新启动一个新的日志文件。)
我不知道是否有机会将该配置字符串放入 application.properties 中,抱歉...
与您的略有不同,我的 pom.xml 引用了替代日志框架(ch.qos.logback),这里是:
In my case I had to put the configuration file "logback.xml" inside the folder src/main/resources...
It is highly customizable but you can start with something like this (both STDOUT - the console - and a FILE are simultaneously written):
The example above writes an "yourappname.log" file inside the "/logs" folder (C:\logs\yourappname.log if you're using Windows and your app is running on drive C:, on /logs/yourappname.log if you're in Linux or MacOS).
Furthermore, the above configuration file provides a time-based LogRotation mechanism (which means that, at regular time intervals - 7 days in this case - the logfile is compressed and archived in a tar.gz fashion and a new one is started fresh.)
I have no idea about the opportunity to put that configuration string inside the application.properties, sorry...
Slightly different from yours, my pom.xml refers to an alternative log framework (ch.qos.logback), here it is:
今年是
IntelliJ IDEA 2023.1.1 (CE)
和Springboot 版本 3.0.6
的一年,尽管文档超级丰富,但仍使用Logback
>(Springboot
附带的默认日志记录包),记录到文件(而不是记录到控制台),对我来说是一场噩梦。我终于成功地让它工作了,因此为了所有人的利益,我发布了已解决的关键障碍:
application.properties
对于文件日志记录的工作至关重要。它应该位于src/main/resource
下。application.properties
应包含单独< /a> 日志文件位置及其名称指令(应忽略“未使用的属性”警告):logback-spring.xml
应为位于src/main/resource
(与“application.properties”相同的位置)It is the year of
IntelliJ IDEA 2023.1.1 (CE)
andSpringboot version 3.0.6
and, despite the super-rich documentation, usingLogback
(the default logging package that comes withSpringboot
), to log to a file (instead of logging to the console), proved to be a nightmare for me.I finally managed to make it work, so for the benefit of all, I am posting the key obstacles solved:
application.properties
is critical for file logging to work. It should be located undersrc/main/resource
.application.properties
should contain separate directives for the log file location and for its name (the "Unused property" warnings should be ignored):logback-spring.xml
should be located undersrc/main/resource
(same place as 'application.properties')