Setup Logback to store logs in a file

This commit is contained in:
Julia Cavanaugh 2023-11-29 21:23:59 -06:00
parent fc11993630
commit 2e505d17bc
11 changed files with 140 additions and 44 deletions

1
.gitignore vendored
View File

@ -1,5 +1,6 @@
HELP.md
target/
logs/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/

View File

@ -1,7 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Deploy" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<option name="ACTIVE_PROFILES" />
<module name="UBFunkeysServer" />
<module name="Source Code" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.icedberries.UBFunkeysServer.UBFunkeysServerApplication" />
<method v="2">
<option name="Make" enabled="true" />

17
pom.xml
View File

@ -81,6 +81,23 @@
<artifactId>spring-test</artifactId>
<version>5.3.20</version>
</dependency>
<!-- Logback and SLF4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>

View File

@ -12,6 +12,8 @@ import javagrinko.spring.tcp.Connection;
import javagrinko.spring.tcp.Server;
import javagrinko.spring.tcp.TcpController;
import javagrinko.spring.tcp.TcpHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.Element;
@ -24,8 +26,12 @@ import java.util.UUID;
@TcpController
public class ArkOneController implements TcpHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
public static final String IP_ADDRESS = "127.0.0.1";
private static final String LOG_BASE = "[ArkOne]";
@Autowired
private Server server;
@ -59,7 +65,7 @@ public class ArkOneController implements TcpHandler {
public void receiveData(Connection connection, byte[] data) {
// Log the received request
String xmlData = new String(data);
System.out.println("[ArkOne] New Request: " + xmlData);
log.info("{} New Request: {}", LOG_BASE, xmlData);
// Create a list of responses to send back
ArrayList<String> responses = new ArrayList<>();
@ -224,7 +230,7 @@ public class ArkOneController implements TcpHandler {
case "2":
//TODO: IMPLEMENT CHAT - For now throw unhandled
responses.add("<unknown />");
System.out.println("[ArkOne][ERROR] Unhandled command: " + commandInfo.getNodeName());
log.error("{} Unhandled command: {}", LOG_BASE, commandInfo.getNodeName());
//responses.add(chatPlugin.JoinChat());
break;
case "5":
@ -232,7 +238,7 @@ public class ArkOneController implements TcpHandler {
break;
default:
responses.add("<unknown />");
System.out.println("[ArkOne][Error] Unhandled 'jn' route to plugin: " + routingString.get(1));
log.error("{} Unhandled 'jn' route to plugin: {}", LOG_BASE, routingString.get(1));
break;
}
break;
@ -246,7 +252,7 @@ public class ArkOneController implements TcpHandler {
break;
default:
responses.add("<unknown />");
System.out.println("[ArkOne][Error] Unhandled 'sp' route to plugin: " + routingString.get(1));
log.error("{} Unhandled 'sp' route to plugin: {}", LOG_BASE, routingString.get(1));
break;
}
break;
@ -254,12 +260,11 @@ public class ArkOneController implements TcpHandler {
// -------------------------------------------------------------------------- \\
default:
responses.add("<unknown />");
System.out.println("[ArkOne][ERROR] Unhandled command: " + commandInfo.getNodeName());
log.error("{} Unhandled command: {}", LOG_BASE, commandInfo.getNodeName());
break;
}
} catch (Exception e) {
System.out.println("[ArkOne][ERROR] Unknown error occurred: ");
e.printStackTrace();
log.error("{} Unknown error occurred", LOG_BASE, e);
responses.add("<unknown />");
}
}
@ -274,10 +279,9 @@ public class ArkOneController implements TcpHandler {
connection.send(outputStream.toByteArray());
System.out.println("[ArkOne] Response: " + response);
log.info("{} Response: {}", LOG_BASE, response);
} catch (IOException e) {
System.out.println("[ArkOne][ERROR] Unknown error occurred: ");
e.printStackTrace();
log.error("{} Unknown error occurred", LOG_BASE, e);
}
}
}

View File

@ -4,6 +4,8 @@ import com.icedberries.UBFunkeysServer.domain.User;
import com.icedberries.UBFunkeysServer.service.UserService;
import javagrinko.spring.tcp.Connection;
import javagrinko.spring.tcp.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
@ -22,6 +24,10 @@ import java.util.UUID;
@Service
public class ArkOneSender {
private final Logger log = LoggerFactory.getLogger(getClass());
private final String LOG_BASE = "[ArkOne]";
@Autowired
Server server;
@ -78,8 +84,7 @@ public class ArkOneSender {
return;
} catch (IOException e) {
System.out.println("[ArkOne][ERROR] Failed to send message to user [" + clientId + "]: " + message);
e.printStackTrace();
log.error("{} Failed to send message to user [{}]: {}", LOG_BASE, clientId, message, e);
}
}
}

View File

@ -4,6 +4,8 @@ import com.icedberries.UBFunkeysServer.ArkOne.ArkOneParser;
import com.icedberries.UBFunkeysServer.service.FileService;
import javagrinko.spring.tcp.Connection;
import javagrinko.spring.tcp.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.mock.web.MockMultipartFile;
@ -30,6 +32,10 @@ import static java.nio.charset.StandardCharsets.UTF_8;
@Service
public class GalaxyPlugin {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final String LOG_BASE = "[ArkOne]";
@Autowired
Server server;
@ -207,7 +213,7 @@ public class GalaxyPlugin {
}
break;
default:
System.out.println("[ArkOne][ERROR] gls had a category value of: " + category);
log.error("{} gls had a category value of: {}", LOG_BASE, category);
break;
}

View File

@ -8,6 +8,8 @@ import com.icedberries.UBFunkeysServer.service.RainbowShootoutService;
import com.icedberries.UBFunkeysServer.service.UserService;
import javagrinko.spring.tcp.Connection;
import javagrinko.spring.tcp.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@ -26,6 +28,10 @@ import java.util.UUID;
@Service
public class UserPlugin {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final String LOG_BASE = "[ArkOne]";
@Autowired
Server server;
@ -496,7 +502,7 @@ public class UserPlugin {
}
break;
default:
System.out.println("[ArkOne][ERROR] Unhandled plugin with ID [" + plugin + "] in UserPlugin.InvitePlayer!");
log.error("{} Unhandled plugin with ID [{}] in UserPlugin.InvitePlayer", LOG_BASE, plugin);
return "<notneeded />";
}
@ -533,7 +539,7 @@ public class UserPlugin {
.ifPresent(myRS -> rainbowShootoutService.delete(myRS));
break;
default:
System.out.println("[ArkOne][ERROR] Unhandled plugin with ID [" + plugin + "] in UserPlugin.InviteBuddyResponse!");
log.error("{} Unhandled plugin with ID [{}] in UserPlugin.InviteBuddyResponse", LOG_BASE, plugin);
return "<notneeded />";
}
}

View File

@ -11,6 +11,8 @@ import com.icedberries.UBFunkeysServer.service.LevelService;
import com.icedberries.UBFunkeysServer.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
@ -51,6 +53,13 @@ import java.util.stream.Collectors;
@RestController
public class GalaxyServer {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final String LOG_BASE = "[Galaxy]";
private static final String LOG_GET = "[GET]";
private static final String LOG_PUT = "[PUT]";
private static final String LOG_POST = "[POST]";
@Autowired
private EmailService emailService;
@ -76,7 +85,7 @@ public class GalaxyServer {
// Change the file path to use spaces
pathToFile = StringUtils.removeStart(pathToFile.replace("%20", " "), "/");
System.out.println("[Galaxy][GET] Request for file: " + pathToFile);
log.info("{}{} Request for file: {}", LOG_BASE, LOG_GET, pathToFile);
int errorCode = 0;
@ -103,13 +112,12 @@ public class GalaxyServer {
imageData = FileCopyUtils.copyToByteArray(resource.getInputStream());
} catch (IOException e) {
// Print the error to the log but let the data be null, so we return a bad data response
System.out.println("[Galaxy][GET] Exception thrown when loading image: ");
e.printStackTrace();
log.error("{}{} Exception thrown when loading image", LOG_BASE, LOG_GET, e);
}
// Verify that something was loaded
if (imageData == null) {
System.out.println("[Galaxy][GET][ERROR] Game maker image not found!");
log.error("{}{} Game maker image not found!", LOG_BASE, LOG_GET);
errorCode = HttpServletResponse.SC_NOT_FOUND;
response.sendError(errorCode);
return;
@ -123,9 +131,9 @@ public class GalaxyServer {
IOUtils.copy(fileContentStream, response.getOutputStream());
// Flush the buffer
// MIGHT ALSO NEED TO SET THE FILE CONTENT LENGTH AS A HEADER
//todo: MIGHT ALSO NEED TO SET THE FILE CONTENT LENGTH AS A HEADER?
response.flushBuffer();
System.out.println("[Galaxy][GET] Game maker image sent!");
log.info("{}{} Game maker image sent", LOG_BASE, LOG_GET);
return;
}
@ -150,15 +158,13 @@ public class GalaxyServer {
}
} catch (IOException e) {
// File read errors caught here
System.out.println("[Galaxy][GET][ERROR] Problem loading file: " + pathToFile);
e.printStackTrace();
log.error("{}{} Problem loading file at: {}", LOG_BASE, LOG_GET, pathToFile, e);
// Set the error code
errorCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
} catch (Exception e) {
// File doesn't exist error caught here
System.out.println(e.getMessage());
e.printStackTrace();
log.error("{}{} Exception thrown while retrieving update file: {}", LOG_BASE, LOG_GET, pathToFile, e);
// Set the error code
errorCode = HttpServletResponse.SC_NOT_FOUND;
@ -168,8 +174,7 @@ public class GalaxyServer {
try {
response.sendError(errorCode);
} catch (IOException e) {
System.out.println("[Galaxy][GET][ERROR] Problem sending error response to client: ");
e.printStackTrace();
log.error("{}{} Problem sending error response to client", LOG_BASE, LOG_GET, e);
}
}
}
@ -177,7 +182,7 @@ public class GalaxyServer {
@PutMapping("/**")
public void GalaxyPutResponse(@RequestBody byte[] request, HttpServletRequest servletRequest) {
System.out.println("[Galaxy][PUT] Saving image file: " + servletRequest.getRequestURI());
log.info("{}{} Saving image file: {}", LOG_BASE, LOG_PUT, servletRequest.getRequestURI());
fileService.saveGameMakerImage(request, servletRequest.getRequestURI().replace("data/", ""));
}
@ -189,7 +194,7 @@ public class GalaxyServer {
@PostMapping("/")
public ResponseEntity<String> GalaxyPostResponse(@RequestBody String xmlBody) {
// Log the request
System.out.println("[Galaxy][POST] Request: " + xmlBody);
log.info("{}{} Request: {}", LOG_BASE, LOG_POST, xmlBody);
try {
// Parse the xml body of the request
@ -239,17 +244,16 @@ public class GalaxyServer {
response = getLevelInfo((Element)nodes.item(0));
break;
default:
System.out.println("[Galaxy][POST][ERROR] Unhandled type of request for: " + command);
log.error("{}{} Unhandled type of request for: {}", LOG_BASE, LOG_POST, command);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// Log the response
System.out.println(response.getBody());
log.info("{}{} Response: {}", LOG_BASE, LOG_POST, response.getBody());
// Return to the client
return response;
} catch (ParserConfigurationException | IOException | SAXException e) {
//System.out.println("[Galaxy][POST][ERROR] Thrown Error: ");
e.printStackTrace();
log.error("{}{} Error thrown", LOG_BASE, LOG_POST, e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@ -351,8 +355,7 @@ public class GalaxyServer {
profileData = ArkOneParser.RemoveXMLTag(newDocument);
} catch (ParserConfigurationException | TransformerException e) {
System.out.println("[Galaxy][POST] Exception thrown when saving crib: ");
e.printStackTrace();
log.error("{}{} Exception thrown when saving crib", LOG_BASE, LOG_POST, e);
resultCode = 1;
reason = "Error saving crib! Please try again later...";
}
@ -491,8 +494,7 @@ public class GalaxyServer {
levelData = ArkOneParser.RemoveXMLTag(newDocument);
} catch (ParserConfigurationException | TransformerException e) {
System.out.println("[Galaxy][POST] Exception thrown when saving crib: ");
e.printStackTrace();
log.error("{}{} Exception thrown when saving level", LOG_BASE, LOG_POST, e);
responseCode = 1;
}
@ -562,7 +564,7 @@ public class GalaxyServer {
break;
default:
// Unhandled type
System.out.println("[Galaxy][POST] Unhandled type: " + type);
log.error("{}{} Unhandled type: {}", LOG_BASE, LOG_POST, type);
sortedLevels = new ArrayList<>();
break;
}
@ -655,7 +657,7 @@ public class GalaxyServer {
searchResults = levelService.findAllByGameNameAndLevelName(gameName, searchKeyword);
break;
default:
System.out.println("[GALAXY][POST] Unhandled Game Maker search type: " + searchType);
log.error("{}{} Unhandled Game Maker search type: {}", LOG_BASE, LOG_POST, searchType);
searchResults = new ArrayList<>();
break;
}

View File

@ -1,6 +1,8 @@
package com.icedberries.UBFunkeysServer.service.impl;
import com.icedberries.UBFunkeysServer.service.EmailService;
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.core.io.ByteArrayResource;
@ -17,6 +19,10 @@ import javax.mail.internet.MimeMessage;
@Service("emailService")
public class EmailServiceImpl implements EmailService {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final String LOG_BASE = "[Galaxy]";
@Autowired
private JavaMailSender mailsender;
@ -45,11 +51,10 @@ public class EmailServiceImpl implements EmailService {
try {
mailsender.send(preparator);
System.out.println("[GALAXY][POST] Email send successfully to: " + to);
log.info("{} Email sent successfully to: {}", LOG_BASE, to);
return true;
} catch(MailException e) {
System.out.println("[GALAXY][POST][ERROR] Unable to send email to: " + to);
e.printStackTrace();
log.error("{} Unable to send email to: {}", LOG_BASE, to, e);
return false;
}
}

View File

@ -2,6 +2,8 @@ package com.icedberries.UBFunkeysServer.service.impl;
import com.icedberries.UBFunkeysServer.property.FileStorageProperty;
import com.icedberries.UBFunkeysServer.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
@ -20,6 +22,10 @@ import java.nio.file.StandardCopyOption;
@Service
public class FileServiceImpl implements FileService {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final String LOG_BASE = "[Galaxy]";
private final Path fileStorageLocation;
@Autowired
@ -38,7 +44,7 @@ public class FileServiceImpl implements FileService {
InputStream imageContentStream = new ByteArrayInputStream(imageData);
Path pathToFile = Paths.get(fileStorageLocation.toString(), subDirAndFileName);
Files.copy(imageContentStream, pathToFile, StandardCopyOption.REPLACE_EXISTING);
System.out.println("[Galaxy][PUT] Image saved successfully");
log.info("{}[PUT] Image saved successfully", LOG_BASE);
} catch(Exception e) {
throw new RuntimeException("Could not store the profile file. Error: " + e.getMessage());
}
@ -50,6 +56,7 @@ public class FileServiceImpl implements FileService {
Files.createDirectories(fileStorageLocation.resolve(subDir));
Files.copy(file.getInputStream(), fileStorageLocation.resolve(subDir).resolve(file.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
} catch(Exception e) {
log.error("{} Failed to save profile part", LOG_BASE, e);
throw new RuntimeException("Could not store the profile file. Error: " + e.getMessage());
}
}
@ -66,6 +73,7 @@ public class FileServiceImpl implements FileService {
return null;
}
} catch(MalformedURLException e) {
log.error("{} Failed to load resource at: {}", LOG_BASE, path, e);
throw new RuntimeException("Error: " + e.getMessage());
}
}

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="LOGS" value="./logs" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<file>${LOGS}/ub-funkeys-server.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>ub-funkeys-server.%i.log.zip</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>10</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>10 MB</maxFileSize>
</triggeringPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{ISO8601} [%t] %-5p %c{0} - %m%n</Pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
</root>
</configuration>