Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: raise library test coverage #349

Closed
wants to merge 25 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
rust_versions: ["stable", "1.69"]
rust_versions: ["stable", "1.70"]
os: [ubuntu-latest, windows-latest]
steps:
- name: Checkout the source code
Expand Down Expand Up @@ -63,7 +63,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
rust_versions: ["stable", "1.69"]
rust_versions: ["stable", "1.70"]
steps:
- name: Checkout the source code
uses: actions/checkout@v4
Expand Down
11 changes: 8 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ repository = "https://github.com/estk/log4rs"
readme = "README.md"
keywords = ["log", "logger", "logging", "log4"]
edition = "2018"
rust-version = "1.69"
rust-version = "1.70"

[features]
default = ["all_components", "config_parsing", "yaml_format"]
Expand Down Expand Up @@ -62,13 +62,13 @@ fnv = "1.0"
humantime = { version = "2.1", optional = true }
log = { version = "0.4.20", features = ["std"] }
log-mdc = { version = "0.1", optional = true }
serde = { version = "1.0", optional = true, features = ["derive"] }
serde = { version = "1.0.196", optional = true, features = ["derive"] }
serde-value = { version = "0.7", optional = true }
thread-id = { version = "4", optional = true }
typemap-ors = { version = "1.0.0", optional = true }
serde_json = { version = "1.0", optional = true }
serde_yaml = { version = "0.9", optional = true }
toml = { version = "0.8", optional = true }
toml = { version = "0.8.10", optional = true }
parking_lot = { version = "0.12.0", optional = true }
rand = { version = "0.8", optional = true}
thiserror = "1.0.15"
Expand All @@ -88,6 +88,7 @@ streaming-stats = "0.2.3"
humantime = "2.1"
tempfile = "3.8"
mock_instant = "0.3"
serde_test = "1.0.176"

[[example]]
name = "json_logger"
Expand All @@ -108,3 +109,7 @@ required-features = ["file_appender", "rolling_file_appender", "size_trigger"]
[[example]]
name = "multi_logger_config"
required-features = ["yaml_format", "config_parsing"]

[[example]]
name = "color_control"
required-features = ["yaml_format", "config_parsing"]
21 changes: 2 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,11 @@
[![crates.io](https://img.shields.io/crates/v/log4rs.svg)](https://crates.io/crates/log4rs)
[![License: MIT OR Apache-2.0](https://img.shields.io/crates/l/clippy.svg)](#license)
![CI](https://github.com/estk/log4rs/workflows/CI/badge.svg)
[![Minimum rustc version](https://img.shields.io/badge/rustc-1.69+-green.svg)](https://github.com/estk/log4rs#rust-version-requirements)
[![Minimum rustc version](https://img.shields.io/badge/rustc-1.70+-green.svg)](https://github.com/estk/log4rs#rust-version-requirements)

log4rs is a highly configurable logging framework modeled after Java's Logback
and log4j libraries.

## Warning

If you are using the file rotation in your configuration there is a known
substantial performance issue so listen up! By default the `gzip` feature
is enabled and when rolling files it will zip log archives automatically.
This is a problem when the log archives are large as the zip happens in the
main thread and will halt the process while the zip is completed. Be advised
that the `gzip` feature will be removed from default features as of `1.0`.

The methods to mitigate this are as follows.

1. Use the `background_rotation` feature which spawns an os thread to do the compression.
1. Disable the `gzip` feature with `--no-default-features`.
1. Ensure the archives are small enough that the compression time is acceptable.

For more information see the PR that added [`background_rotation`](https://github.com/estk/log4rs/pull/117).

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why rm?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so, i just pulled the thread and although gzip is no-longer part of the default features, I still think a warning regarding the use of gzip is important to be featured in the readme... perhaps not as prominently. Also, this change should be pulled out into a separate PR.

## Quick Start

log4rs.yaml:
Expand Down Expand Up @@ -71,7 +54,7 @@ fn main() {

## Rust Version Requirements

1.69
1.70

## Building for Dev

Expand Down
2 changes: 1 addition & 1 deletion docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ other components, the default (and only supported) policy is `kind: compound`.
The _trigger_ field is used to dictate when the log file should be rolled. It
supports two types: `size`, and `time`.

For `size`, it require a _limit_ field. The _limit_ field is a string which defines the maximum file size
For `size`, it requires a _limit_ field. The _limit_ field is a string which defines the maximum file size
prior to a rolling of the file. The limit field requires one of the following
units in bytes, case does not matter:

Expand Down
31 changes: 31 additions & 0 deletions examples/color_control.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use log::{error, info};
use log4rs;
use serde_yaml;
use std::env;

fn main() {
let config_str = include_str!("sample_config.yml");
let config = serde_yaml::from_str(config_str).unwrap();
log4rs::init_raw_config(config).unwrap();

let no_color = match env::var("NO_COLOR") {
Ok(no_color) => no_color,
Err(_) => "0".to_string(),
};
let clicolor_force = match env::var("CLICOLOR_FORCE") {
Ok(clicolor_force) => clicolor_force,
Err(_) => "0".to_string(),
};
let cli_color = match env::var("CLICOLOR") {
Ok(cli_color) => cli_color,
Err(_) => "0".to_string(),
};
info!(
"NO_COLOR: {}, CLICOLOR_FORCE: {}, CLICOLOR: {}",
no_color, clicolor_force, cli_color
);
error!(
"NO_COLOR: {}, CLICOLOR_FORCE: {}, CLICOLOR: {}",
no_color, clicolor_force, cli_color
);
}
114 changes: 114 additions & 0 deletions src/append/console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,3 +263,117 @@ impl Deserialize for ConsoleAppenderDeserializer {
Ok(Box::new(appender.build()))
}
}

#[cfg(test)]
mod test {
use super::*;
use crate::encode::Write;

#[test]
fn test_append() {
use log::Level;

// Build a std out appender
let appender = ConsoleAppender::builder()
.tty_only(false)
.target(Target::Stdout)
.encoder(Box::new(PatternEncoder::new("{m}{n}")))
.build();

assert!(appender
.append(
&Record::builder()
.level(Level::Debug)
.target("target")
.module_path(Some("module_path"))
.file(Some("file"))
.line(Some(100))
.args(format_args!("{}", "message"))
.build()
)
.is_ok());

// No op, but test coverage :)
appender.flush();
}

#[test]
fn test_builder() {
// Build a std out appender
let _appender = ConsoleAppender::builder()
.tty_only(false)
.target(Target::Stdout)
.encoder(Box::new(PatternEncoder::new("{m}{n}")))
.build();

// Build a std err appender
let _appender = ConsoleAppender::builder()
.tty_only(false)
.target(Target::Stderr)
.encoder(Box::new(PatternEncoder::new("{m}{n}")))
.build();

// Build a default encoder appender
let _appender = ConsoleAppender::builder()
.tty_only(true)
.target(Target::Stderr)
.build();
}

#[test]
#[cfg(feature = "config_parsing")]
fn test_config_deser() {
use crate::{config::Deserializers, encode::EncoderConfig};
use serde_value::Value;
use std::collections::BTreeMap;
let deserializer = ConsoleAppenderDeserializer;

let targets = vec![ConfigTarget::Stdout, ConfigTarget::Stderr];

for target in targets {
let console_cfg = ConsoleAppenderConfig {
target: Some(target),
encoder: Some(EncoderConfig {
kind: "pattern".to_owned(),
config: Value::Map(BTreeMap::new()),
}),
tty_only: Some(true),
};
assert!(deserializer
.deserialize(console_cfg, &Deserializers::default())
.is_ok());
}
}

fn write_test(mut writer: WriterLock) {
use std::io::Write;

assert_eq!(writer.write(b"Write log\n").unwrap(), 10);
assert!(writer.set_style(&Style::new()).is_ok());
assert!(writer.write_all(b"Write All log\n").is_ok());
assert!(writer.write_fmt(format_args!("{} \n", "normal")).is_ok());
assert!(writer.flush().is_ok());
}

#[test]
fn test_tty() {
// Note that this fails in GitHub Actions and therefore does not
// show as covered.
let w = match ConsoleWriter::stdout() {
Some(w) => w,
None => return,
};

let tty = Writer::Tty(w);
assert!(tty.is_tty());

write_test(tty.lock());
}

#[test]
fn test_raw() {
let raw = Writer::Raw(StdWriter::stdout());
assert!(!raw.is_tty());
write_test(raw.lock());
}
}
61 changes: 57 additions & 4 deletions src/append/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ mod test {
use super::*;

#[test]
fn create_directories() {
fn test_create_directories() {
let tempdir = tempfile::tempdir().unwrap();

FileAppender::builder()
Expand All @@ -173,11 +173,64 @@ mod test {
}

#[test]
fn append_false() {
fn test_append_trait() {
use log::Level;

let tempdir = tempfile::tempdir().unwrap();
FileAppender::builder()
.append(false)
let appender = FileAppender::builder()
.build(tempdir.path().join("foo.log"))
.unwrap();

log_mdc::insert("foo", "bar");
let res = appender.append(
&Record::builder()
.level(Level::Debug)
.target("target")
.module_path(Some("module_path"))
.file(Some("file"))
.line(Some(100))
.args(format_args!("{}", "message"))
.build(),
);
assert!(res.is_ok());

appender.flush();
}

#[test]
fn test_append_builder() {
let append_choices = vec![true, false];
let tempdir = tempfile::tempdir().unwrap();

for do_append in append_choices {
// No actionable test
FileAppender::builder()
.append(do_append)
.build(tempdir.path().join("foo.log"))
.unwrap();
}
}

#[test]
#[cfg(feature = "config_parsing")]
fn test_config_deser() {
use crate::config::Deserializers;
use serde_value::Value;
use std::collections::BTreeMap;

let tempdir = tempfile::tempdir().unwrap();
let file_cfg = FileAppenderConfig {
path: tempdir.path().join("foo.log").to_str().unwrap().to_owned(),
encoder: Some(EncoderConfig {
kind: "pattern".to_owned(),
config: Value::Map(BTreeMap::new()),
}),
append: Some(true),
};

let deserializer = FileAppenderDeserializer;

let res = deserializer.deserialize(file_cfg, &Deserializers::default());
assert!(res.is_ok());
}
}
Loading
Loading