Skip to content

Commit

Permalink
fix: add try/catch in logging (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrey Oskin committed Nov 8, 2022
1 parent 43b06f9 commit a012047
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
4 changes: 2 additions & 2 deletions Project.toml
Original file line number Diff line number Diff line change
@@ -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"

Expand Down
18 changes: 14 additions & 4 deletions src/logging.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ struct TelegramLogger <: AbstractLogger
fmt::Function
min_level::LogLevel
async::Bool
silent_errors::Bool
end

"""
Expand All @@ -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)
Expand All @@ -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

Expand Down

0 comments on commit a012047

Please sign in to comment.