From a012047bf4d51dacb4aaf957011bcd9caca0964a Mon Sep 17 00:00:00 2001 From: Andrey Oskin Date: Tue, 8 Nov 2022 10:29:11 +0200 Subject: [PATCH] fix: add try/catch in logging (#18) --- Project.toml | 4 ++-- src/logging.jl | 18 ++++++++++++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/Project.toml b/Project.toml index 14dcf67..eb0d05c 100644 --- a/Project.toml +++ b/Project.toml @@ -1,14 +1,14 @@ name = "Telegram" uuid = "1da6f4ae-116c-4c38-8ee9-19974ff3601d" authors = ["Andrey Oskin"] -version = "1.1.3" +version = "1.1.4" [deps] HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" JSON3 = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" [compat] -HTTP = "0.8, 0.9, 1.0" +HTTP = "0.8, 0.9, 1" JSON3 = "1" julia = "1.3" diff --git a/src/logging.jl b/src/logging.jl index fe7616a..c614a6e 100644 --- a/src/logging.jl +++ b/src/logging.jl @@ -3,6 +3,7 @@ struct TelegramLogger <: AbstractLogger fmt::Function min_level::LogLevel async::Bool + silent_errors::Bool end """ @@ -16,9 +17,10 @@ Creates logger, which output log messages to Telegram channel. - `fmt`: function which accepts (`level`, `_module`, `group`, `id`, `file`, `line`) arguments and outputs message prefix. More details can be found in [Logging](https://docs.julialang.org/en/v1/stdlib/Logging/#Logging.handle_message) module. By default each messages is prepended with uppercase level, e.g. "INFO: " and the like. - `min_level`: minimum level of log messages which is going to be processed. - `async`: send messages in `sync` or `async` mode. Since telegram messages can take some time to be send, it make sense to set this parameter to `true`, so messages is send in the background with little impact on main program. But since in one run scripts main julia process can be finished before async message is sent, it make sense to set this parameter to `false` +- `silent_errors`: by default, if there was an error during sending a message, it will be printed in `stderr` channel. If you want to silence this output, set `silent_errors` to `true`. """ -function TelegramLogger(tg::TelegramClient; fmt = tg_formatter, min_level = Info, async = true) - return TelegramLogger(tg, fmt, min_level, async) +function TelegramLogger(tg::TelegramClient; fmt = tg_formatter, min_level = Info, async = true, silent_errors = false) + return TelegramLogger(tg, fmt, min_level, async, silent_errors) end function tg_formatter(level, _module, group, id, file, line) @@ -36,9 +38,17 @@ function handle_message(tglogger::TelegramLogger, level, message, _module, group end text = String(take!(iob)) if tglogger.async - @async sendMessage(tglogger.tg; text = text) + @async try + sendMessage(tglogger.tg; text = text) + catch err + tglogger.silent_errors || error(err) + end else - sendMessage(tglogger.tg; text = text) + try + sendMessage(tglogger.tg; text = text) + catch err + tglogger.silent_errors || error(err) + end end end