Skip to content

Commit a634aa1

Browse files
authored
Introduce logging
1 parent 13e01a2 commit a634aa1

File tree

5 files changed

+56
-12
lines changed

5 files changed

+56
-12
lines changed

build.gradle

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ dependencies {
1919
implementation 'com.github.kilianB:JImageHash:3.0.0'
2020
implementation 'com.h2database:h2:1.4.200'
2121

22+
implementation 'org.apache.logging.log4j:log4j-core:2.13.3'
23+
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.11.3'
24+
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.11.3"
25+
2226
testCompile 'junit:junit:4.12'
2327
}
2428

log4j2.yaml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
Configuration:
2+
name: SimilarImagesBot
3+
4+
Appenders:
5+
Console:
6+
- name: Console
7+
target: SYSTEM_OUT
8+
PatternLayout:
9+
Pattern: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
10+
11+
Loggers:
12+
Root:
13+
level: debug
14+
AppenderRef:
15+
- ref: Console
16+
level: debug
17+

src/main/java/com/annimon/similarimagesbot/BaseBotHandler.java

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,13 @@
1515
import com.pengrad.telegrambot.model.PhotoSize;
1616
import com.pengrad.telegrambot.model.Update;
1717
import com.pengrad.telegrambot.request.GetUpdates;
18+
import org.apache.logging.log4j.LogManager;
19+
import org.apache.logging.log4j.Logger;
1820

1921
public abstract class BaseBotHandler {
2022

23+
protected static final Logger LOGGER = LogManager.getLogger(BaseBotHandler.class);
24+
2125
private final Comparator<PhotoSize> photoSizeComparator = Comparator
2226
.comparingInt(ps -> ps.width() * ps.height());
2327

@@ -33,23 +37,26 @@ public BaseBotHandler(String botToken) {
3337

3438
public void run() {
3539
int oldLastUpdateId = readLastUpdateId();
40+
LOGGER.debug("Start updates listener from {}", oldLastUpdateId);
3641
bot.setUpdatesListener(updates -> {
3742
final var filteredUpdates = updates.stream()
3843
.filter(u -> u.updateId() > oldLastUpdateId)
3944
.collect(Collectors.toList());
4045
handleUpdates(filteredUpdates);
41-
int newLastUpdateId = getLastUpdateIdFromUpdatesList(updates, oldLastUpdateId);
42-
writeLastUpdateId(newLastUpdateId + 1);
46+
int nextLastUpdateId = geNextUpdateId(updates, oldLastUpdateId);
47+
writeNextUpdateId(nextLastUpdateId);
4348
return UpdatesListener.CONFIRMED_UPDATES_ALL;
4449
});
4550
}
4651

4752
public void runOnce() {
4853
int oldLastUpdateId = readLastUpdateId();
54+
LOGGER.debug("Get updates from {}", oldLastUpdateId);
4955
final var updates = bot.execute(new GetUpdates().offset(oldLastUpdateId)).updates();
56+
LOGGER.debug("Handle {} updates", updates.size());
5057
handleUpdates(updates);
51-
int newLastUpdateId = getLastUpdateIdFromUpdatesList(updates, oldLastUpdateId);
52-
writeLastUpdateId(newLastUpdateId + 1);
58+
int newLastUpdateId = geNextUpdateId(updates, oldLastUpdateId);
59+
writeNextUpdateId(newLastUpdateId);
5360
}
5461

5562
protected abstract void handleUpdates(List<Update> updates);
@@ -74,23 +81,33 @@ protected PhotoSize getBiggestPhoto(PhotoSize[] photoSizes) {
7481
.orElse(photoSizes[0]);
7582
}
7683

77-
private int getLastUpdateIdFromUpdatesList(List<Update> updates, int previousUpdateId) {
78-
return updates.stream()
84+
private int geNextUpdateId(List<Update> updates, int previousUpdateId) {
85+
final int lastUpdateId = updates.stream()
7986
.mapToInt(Update::updateId)
8087
.max()
8188
.orElse(previousUpdateId);
89+
final int nextUpdateId;
90+
if (lastUpdateId != previousUpdateId) {
91+
nextUpdateId = lastUpdateId + 1;
92+
} else {
93+
nextUpdateId = lastUpdateId;
94+
}
95+
return nextUpdateId;
8296
}
8397

8498
private int readLastUpdateId() {
8599
try {
86100
return Integer.parseInt(Files.readString(uniqueIdPath));
87101
} catch (IOException ioe) {
102+
LOGGER.error("readLastUpdateId", ioe);
88103
return 0;
89104
}
90105
}
91106

92-
private void writeLastUpdateId(int updateId) {
107+
private void writeNextUpdateId(int updateId) {
93108
try {
94109
Files.writeString(uniqueIdPath, Integer.toString(updateId));
95-
} catch (IOException ignore) {}
110+
} catch (IOException ioe) {
111+
LOGGER.error("writeLastUpdateId", ioe);
112+
}
96113
}}

src/main/java/com/annimon/similarimagesbot/BotHandler.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,12 @@ private Optional<Post> processDelCommand(Matcher m) {
7272
}
7373
final var channelId = Long.parseLong("-100" + m.group(1));
7474
final var messageId = Integer.parseInt(m.group(2));
75+
LOGGER.debug("Delete message {} in {}", messageId, channelId);
7576
bot.execute(new DeleteMessage(channelId, messageId));
7677
try {
7778
indexer.deleteImage(channelId, messageId);
7879
} catch (SQLException ex) {
79-
System.err.println("Cannot delete image in db");
80+
LOGGER.error("Cannot delete image in db", ex);
8081
}
8182
return Optional.of(new Post(channelId, messageId));
8283
}
@@ -88,6 +89,7 @@ private Optional<Post> processCompareCommand(Matcher m) {
8889
final var channelId = Long.parseLong("-100" + m.group(1));
8990
final var messageA = Integer.parseInt(m.group(2));
9091
final var messageB = Integer.parseInt(m.group(3));
92+
LOGGER.debug("Compare messages {} and {} in {}", messageA, messageB, channelId);
9193

9294
// Forward and get photo to compare
9395
var sentA = bot.execute(new ForwardMessage(adminId, channelId, messageA));
@@ -127,7 +129,7 @@ private void processUpdates(List<Update> updates, Set<Post> ignoredPosts) {
127129
similarImagesInfos.add(info);
128130
}
129131
} catch (IOException | SQLException e) {
130-
System.err.format("Error while processing photo in %s%n", linkToMessage(post));
132+
LOGGER.error("Error while processing photo in {}", linkToMessage(post));
131133
}
132134
}
133135
if (!similarImagesInfos.isEmpty()) {

src/main/java/com/annimon/similarimagesbot/Main.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
11
package com.annimon.similarimagesbot;
22

33
import java.util.Optional;
4+
import org.apache.logging.log4j.LogManager;
5+
import org.apache.logging.log4j.Logger;
46

57
public class Main {
68

9+
private static final Logger LOGGER = LogManager.getLogger(Main.class);
10+
711
public static void main(String[] args) {
812
final String botToken = stringProp("BOT_TOKEN")
913
.orElseThrow(() -> new IllegalArgumentException("BOT_TOKEN is required"));
1014
final ImageIndexer indexer = new ImageIndexer();
1115
final var handler = new BotHandler(botToken, indexer);
1216
handler.setAdminId(longProp("ADMIN_ID").orElse(0L));
1317
if (isOnceMode() || (args.length == 1 && args[0].equalsIgnoreCase("once"))) {
14-
System.out.println("Started in once mode");
18+
LOGGER.info("Started in once mode");
1519
handler.runOnce();
1620
} else {
17-
System.out.println("Started in listen mode");
21+
LOGGER.info("Started in listen mode");
1822
handler.run();
1923
}
2024
}

0 commit comments

Comments
 (0)