Skip to content

Commit

Permalink
feat: JSON 方式でログを出力できるように (#207)
Browse files Browse the repository at this point in the history
  • Loading branch information
m1sk9 authored Sep 6, 2024
1 parent 3f4fcca commit 565a7ec
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 32 deletions.
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ features = ["macros", "rt-multi-thread"]

[dependencies.tracing-subscriber]
version = "0.3.18"
features = ["env-filter"]
features = ["env-filter", "json"]

[dependencies.moka]
version = "0.12.7"
Expand Down
5 changes: 5 additions & 0 deletions config/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,8 @@ bypass_guilds: false

# Whether to enable mentions in quoted messages.
citation_mention: false

# Sets the format of babyrite log output.
# * `compact`: output logs in normal format.
# * `json`: Output logs in JSON format. This is the recommended setting if you are using Grafana Loki or similar.
logger_format: 'compact'
31 changes: 19 additions & 12 deletions docs/src/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,20 +48,27 @@ However, the message will be shared to members who do not belong to that guild.

Whether or not to make a quoted message mentions.

## Change the displayed logs
#### `logger_format`

Since babyrite uses [tracing, traching-subscriber](https://github.com/tokio-rs/tracing) for logging, you can change the displayed logs by setting the environment variable `RUST_LOG` at startup.

```shell
RUST_LOG=babyrite=info cargo run
RUST_LOG=babyrite=debug cargo run
RUST_LOG=babyrite=info ./target/release/babyrite
```
> *Available in [v0.10.0](https://github.com/m1sk9/babyrite/releases/tag/babyrite-v0.10.0)*
>
> *Expected type: string*

When `RUST_LOG` is not set, running cargo run or the binary directly will display babyrite logs including debug events. (default)
Sets the format of the log output. Both will show logs above babyrite's `INFO` level (when using Docker images).

If you want to change the type of log displayed, pass `RUST_LOG` as an environment variable.
* `compact`: output logs in normal format. (format: `{time} {level} {target} {message}`)
* `json`: Output logs in JSON format. This is the recommended setting if you are using [Grafana Loki](https://grafana.com/oss/loki/) or similar.

> [!NOTE]
> [!TIP]
>
> The following string can also be used: `Compact`, `Json`
>
> `babyrite=` specifies the logs for the babyrite. Therefore, if you specify a crate other than babyrite in RUST_LOG (e.g. `RUST_LOG=serenity=info`), the logs for that crate will be displayed.
> ```rs
> #[derive(Debug, Deserialize)]
> pub enum LoggerFormat {
> #[serde(alias = "compact")]
> Compact,
> #[serde(alias = "json")]
> Json,
> }
> ```
49 changes: 43 additions & 6 deletions src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,21 @@ impl EventHandler for BabyriteHandler {
return;
}

tracing::info!(
"* Request from {}: Start processing...",
message.author.tag(),
);

let target_channel = match get_channel_list_cache(&ctx, ids.guild, ids.channel).await {
Ok(channel) => channel,
Ok(channel) => {
tracing::info!(
"{} - Message retrieved: {}({})",
message.author.tag(),
channel.name,
channel.id
);
channel
}
Err(e) => {
tracing::error!(
"Failed to retrieve channel. It does not exist or the cache is invalid: {:?}",
Expand All @@ -41,19 +54,38 @@ impl EventHandler for BabyriteHandler {
return;
}
};

if target_channel.nsfw {
tracing::warn!(
"{} - Cancel message citation: Target channel was NSFW.",
message.author.tag()
);
return;
}

let target_message = match target_channel.message(&ctx.http, ids.message).await {
Ok(message) => message,
Ok(target) => {
tracing::info!(
"{} - Channel retrieved: {}",
message.author.tag(),
target.id
);
target
}
Err(e) => {
tracing::error!("Failed to retrieve message: {:?}", e);
return;
}
};

if target_channel.nsfw {
return;
}

if !target_message.embeds.is_empty() && target_message.content.is_empty() {
if target_channel.nsfw {
tracing::warn!(
"{} - Cancel message citation: Message with embedding.",
message.author.tag()
);
return;
}
return;
}

Expand Down Expand Up @@ -94,6 +126,11 @@ impl EventHandler for BabyriteHandler {
{
tracing::error!("Failed to send message: {:?}", why);
}

tracing::info!(
"* Request from {}: Successful citation.",
message.author.tag()
);
}

async fn ready(&self, ctx: Context, client: Ready) {
Expand Down
39 changes: 26 additions & 13 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::model::config::BabyriteConfig;
use model::config::LoggerFormat;
#[deny(unused_imports)]
use serenity::prelude::GatewayIntents;
use tracing_subscriber::{EnvFilter, FmtSubscriber};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

mod env;
mod handler;
Expand All @@ -11,28 +12,40 @@ mod model;
async fn main() -> anyhow::Result<()> {
tracing::info!("Starting babyrite at v{}", env!("CARGO_PKG_VERSION"));

if let Err(cause) = dotenvy::dotenv() {
tracing::warn!(%cause, "Failed to load environment variables from .env file.");
}

let filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("babyrite=debug"));
let subscriber = FmtSubscriber::builder().with_env_filter(filter).finish();
tracing::subscriber::set_global_default(subscriber)
.expect("Failed to set tracing_subscriber as global default.");
dotenvy::dotenv().ok();

BabyriteConfig::init();
let config = BabyriteConfig::get();
tracing::info!("Configuration: {:?}", config);
let envs = env::babyrite_envs();

match config.logger_format {
LoggerFormat::Compact => {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "babyrite=debug,serenity=debug".into()),
)
.with(tracing_subscriber::fmt::layer().compact())
.init();
}
LoggerFormat::Json => {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "babyrite=debug,serenity=debug".into()),
)
.with(tracing_subscriber::fmt::layer().json())
.init();
}
}

tracing::info!("Configuration: {:?}", config);
if config.bypass_guilds {
tracing::warn!(
"The guild bypass setting is enabled. Quote messages between different guilds. "
)
}

let envs = env::babyrite_envs();
// "メッセージの取得", "ギルド内メッセージへのアクセス" に該当する
let intents = GatewayIntents::MESSAGE_CONTENT | GatewayIntents::GUILD_MESSAGES;
let mut client = serenity::Client::builder(&envs.discord_api_token, intents)
.event_handler(handler::BabyriteHandler)
Expand Down
9 changes: 9 additions & 0 deletions src/model/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ use crate::env::babyrite_envs;
pub struct BabyriteConfig {
pub bypass_guilds: bool,
pub citation_mention: bool,
pub logger_format: LoggerFormat,
}

#[derive(Debug, Deserialize)]
pub enum LoggerFormat {
#[serde(alias = "compact")]
Compact,
#[serde(alias = "json")]
Json,
}

pub static BABYRITE_CONFIG: once_cell::sync::OnceCell<BabyriteConfig> =
Expand Down

0 comments on commit 565a7ec

Please sign in to comment.