Skip to content

Commit 28b2e14

Browse files
committed
Use ScopedValue to pass userId information in logs
1 parent 1eaae5d commit 28b2e14

File tree

2 files changed

+50
-20
lines changed

2 files changed

+50
-20
lines changed

src/main/java/com/github/stickerifier/stickerify/bot/Stickerify.java

Lines changed: 49 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import com.pengrad.telegrambot.response.BaseResponse;
3434
import org.slf4j.Logger;
3535
import org.slf4j.LoggerFactory;
36+
import org.slf4j.event.Level;
3637

3738
import java.io.File;
3839
import java.io.IOException;
@@ -54,6 +55,7 @@ public record Stickerify(TelegramBot bot, Executor executor) implements UpdatesL
5455
private static final Logger LOGGER = LoggerFactory.getLogger(Stickerify.class);
5556
private static final String BOT_TOKEN = System.getenv("STICKERIFY_TOKEN");
5657
private static final ThreadFactory VIRTUAL_THREAD_FACTORY = Thread.ofVirtual().name("Virtual-", 0).factory();
58+
public final static ScopedValue<Long> USER = ScopedValue.newInstance();
5759

5860
/**
5961
* Instantiate the bot processing requests with virtual threads.
@@ -78,9 +80,7 @@ public int process(List<Update> updates) {
7880
updates.forEach(update -> executor.execute(() -> {
7981
if (update.message() != null) {
8082
var request = new TelegramRequest(update.message());
81-
LOGGER.atInfo().addKeyValue("request_description", request.getDescription()).log("Received request");
82-
83-
answer(request);
83+
ScopedValue.where(USER, request.getUserId()).run(() -> answer(request));
8484
}
8585
}));
8686

@@ -89,7 +89,7 @@ public int process(List<Update> updates) {
8989

9090
@Override
9191
public void onException(TelegramException e) {
92-
LOGGER.atError().addKeyValue("exception_message", e.getMessage()).log("There was an unexpected failure");
92+
log(Level.ERROR, "exception_message", e.getMessage(), "There was an unexpected failure");
9393
}
9494

9595
@Override
@@ -104,22 +104,52 @@ public void close() {
104104
}
105105

106106
private void answer(TelegramRequest request) {
107+
log(Level.INFO, "Received request");
108+
107109
var file = request.getFile();
108110

109-
if (file != null) {
110-
answerFile(request, file);
111-
} else {
111+
if (file == null) {
112112
answerText(request);
113+
} else {
114+
answerFile(request, file);
113115
}
114116
}
115117

118+
private static void log(Level level, String message) {
119+
LOGGER.atLevel(level)
120+
.addKeyValue("user_id", USER.get())
121+
.log(message);
122+
}
123+
124+
private static void log(Level level, String message, Throwable cause) {
125+
LOGGER.atLevel(level)
126+
.setCause(cause)
127+
.addKeyValue("user_id", USER.get())
128+
.log(message);
129+
}
130+
131+
private static void log(Level level, String key, Object value, String message) {
132+
LOGGER.atLevel(level)
133+
.addKeyValue("user_id", USER.get())
134+
.addKeyValue(key, value)
135+
.log(message);
136+
}
137+
138+
private static void log(Level level, String key, Object value, String message, Throwable cause) {
139+
LOGGER.atLevel(level)
140+
.setCause(cause)
141+
.addKeyValue("user_id", USER.get())
142+
.addKeyValue(key, value)
143+
.log(message);
144+
}
145+
116146
private void answerFile(TelegramRequest request, TelegramFile file) {
117147
if (file == TelegramFile.NOT_SUPPORTED) {
118148
answerText(ERROR, request);
119149
} else if (file.canBeDownloaded()) {
120150
answerFile(request, file.id());
121151
} else {
122-
LOGGER.atInfo().log("Passed-in file is too large");
152+
log(Level.INFO, "Passed-in file is too large");
123153

124154
answerText(FILE_TOO_LARGE, request);
125155
}
@@ -172,25 +202,25 @@ private File retrieveFile(String fileId) throws TelegramApiException, FileOperat
172202

173203
private void processFailure(TelegramRequest request, BaseException e, String fileId) {
174204
if (e instanceof TelegramApiException telegramException) {
175-
processTelegramFailure(request.getDescription(), telegramException, false);
205+
processTelegramFailure(telegramException, false);
176206
}
177207

178208
if (e instanceof CorruptedFileException) {
179-
LOGGER.atInfo().addKeyValue("request_description", request.getDescription()).log("Unable to reply to the request: the file is corrupted");
209+
log(Level.INFO, "Unable to reply to the request: the file is corrupted");
180210
answerText(CORRUPTED, request);
181211
} else {
182-
LOGGER.atWarn().setCause(e).log("Unable to process the file {}", fileId);
212+
log(Level.WARN, "file_id", fileId, "Unable to process file", e);
183213
answerText(ERROR, request);
184214
}
185215
}
186216

187-
private void processTelegramFailure(String requestDescription, TelegramApiException e, boolean logUnmatchedFailure) {
217+
private void processTelegramFailure(TelegramApiException e, boolean logUnmatchedFailure) {
188218
switch (e.getDescription()) {
189-
case "Bad Request: message to be replied not found" -> LOGGER.atInfo().addKeyValue("request_description", requestDescription).log("Unable to reply to the request: the message sent has been deleted");
190-
case "Forbidden: bot was blocked by the user" -> LOGGER.atInfo().addKeyValue("request_description", requestDescription).log("Unable to reply to the request: the user blocked the bot");
219+
case "Bad Request: message to be replied not found" -> log(Level.INFO, "Unable to reply to the request: the message sent has been deleted");
220+
case "Forbidden: bot was blocked by the user" -> log(Level.INFO, "Unable to reply to the request: the user blocked the bot");
191221
default -> {
192222
if (logUnmatchedFailure) {
193-
LOGGER.atError().setCause(e).addKeyValue("request_description", requestDescription).log("Unable to reply to the request");
223+
log(Level.ERROR, "Unable to reply to the request", e);
194224
}
195225
}
196226
}
@@ -199,7 +229,7 @@ private void processTelegramFailure(String requestDescription, TelegramApiExcept
199229
private void answerText(TelegramRequest request) {
200230
var message = request.message();
201231
if (message.text() == null) {
202-
LOGGER.atInfo().addKeyValue("request_message", message).log("An unhandled message type has been received");
232+
log(Level.INFO, "An unhandled message type has been received");
203233
}
204234

205235
answerText(request.getAnswerMessage(), request);
@@ -216,7 +246,7 @@ private void answerText(Answer answer, TelegramRequest request) {
216246
try {
217247
execute(answerWithText);
218248
} catch (TelegramApiException e) {
219-
processTelegramFailure(request.getDescription(), e, true);
249+
processTelegramFailure(e, true);
220250
}
221251
}
222252

@@ -234,10 +264,10 @@ private static void deleteTempFiles(Set<Path> pathsToDelete) {
234264
for (var path : pathsToDelete) {
235265
try {
236266
if (!Files.deleteIfExists(path)) {
237-
LOGGER.atInfo().addKeyValue("file_path", path).log("Unable to delete temp file");
267+
log(Level.INFO, "file_path", path, "Unable to delete temp file");
238268
}
239269
} catch (IOException e) {
240-
LOGGER.atError().setCause(e).addKeyValue("file_path", path).log("An error occurred trying to delete temp file");
270+
log(Level.ERROR, "file_path", path, "An error occurred trying to delete temp file", e);
241271
}
242272
}
243273
}

src/main/java/com/github/stickerifier/stickerify/telegram/model/TelegramRequest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ public String getDescription() {
9393
return description;
9494
}
9595

96-
private Long getUserId() {
96+
public Long getUserId() {
9797
return message.from().id();
9898
}
9999

0 commit comments

Comments
 (0)