diff options
author | Jeff Vander Stoep <jeffv@google.com> | 2022-12-09 14:55:05 +0100 |
---|---|---|
committer | Jeff Vander Stoep <jeffv@google.com> | 2022-12-09 14:57:57 +0100 |
commit | af1e8a3e5b645874632a8c73a0a33c54c920b088 (patch) | |
tree | 40273abb0ded2ea7e95842b8d03d9486ea4c3594 | |
parent | 778e36d6d009e0d49356cd1e49084f82fb127d21 (diff) | |
download | env_logger-af1e8a3e5b645874632a8c73a0a33c54c920b088.tar.gz |
Upgrade env_logger to 0.10.0
This project was upgraded with external_updater.
Usage: tools/external_updater/updater.sh update rust/crates/env_logger
For more info, check https://cs.android.com/android/platform/superproject/+/master:tools/external_updater/README.md
Test: TreeHugger
Change-Id: I4d30e4474a9b9aeaa0e948dddf1cc35e3f226b16
-rw-r--r-- | .cargo_vcs_info.json | 7 | ||||
-rw-r--r-- | Android.bp | 14 | ||||
-rw-r--r-- | CHANGELOG.md | 3 | ||||
-rw-r--r-- | Cargo.lock.saved | 254 | ||||
-rw-r--r-- | Cargo.toml | 104 | ||||
-rw-r--r-- | Cargo.toml.orig | 52 | ||||
-rw-r--r-- | LICENSE-MIT | 2 | ||||
-rw-r--r-- | METADATA | 12 | ||||
-rw-r--r-- | README.md | 12 | ||||
-rw-r--r-- | examples/custom_default_format.rs | 40 | ||||
-rw-r--r-- | examples/custom_format.rs | 54 | ||||
-rw-r--r-- | examples/custom_logger.rs | 62 | ||||
-rw-r--r-- | examples/default.rs | 38 | ||||
-rw-r--r-- | examples/direct_logger.rs | 39 | ||||
-rw-r--r-- | examples/filters_from_code.rs | 20 | ||||
-rw-r--r-- | examples/in_tests.rs | 54 | ||||
-rw-r--r-- | examples/syslog_friendly_format.rs | 24 | ||||
-rw-r--r-- | src/filter/mod.rs | 8 | ||||
-rw-r--r-- | src/fmt/humantime/extern_impl.rs | 2 | ||||
-rw-r--r-- | src/fmt/mod.rs | 14 | ||||
-rw-r--r-- | src/fmt/writer/atty.rs | 17 | ||||
-rw-r--r-- | src/fmt/writer/mod.rs | 3 | ||||
-rw-r--r-- | src/fmt/writer/termcolor/extern_impl.rs | 54 | ||||
-rw-r--r-- | src/fmt/writer/termcolor/mod.rs | 4 | ||||
-rw-r--r-- | src/fmt/writer/termcolor/shim_impl.rs | 1 | ||||
-rw-r--r-- | src/lib.rs | 18 |
26 files changed, 799 insertions, 113 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json index b5ebece..816416d 100644 --- a/.cargo_vcs_info.json +++ b/.cargo_vcs_info.json @@ -1,5 +1,6 @@ { "git": { - "sha1": "04856ac38baf422baebb40729cf51127a75b82ed" - } -} + "sha1": "ff029fa8b6258ed926134f51d38ee85ebd553c35" + }, + "path_in_vcs": "" +}
\ No newline at end of file @@ -42,14 +42,14 @@ rust_test { host_supported: true, crate_name: "env_logger", cargo_env_compat: true, - cargo_pkg_version: "0.9.0", + cargo_pkg_version: "0.10.0", srcs: ["src/lib.rs"], test_suites: ["general-tests"], auto_gen_config: true, test_options: { unit_test: true, }, - edition: "2018", + edition: "2021", rustlibs: [ "liblog_rust", ], @@ -59,10 +59,10 @@ rust_defaults { name: "env_logger_test_defaults", crate_name: "env_logger", cargo_env_compat: true, - cargo_pkg_version: "0.9.0", + cargo_pkg_version: "0.10.0", test_suites: ["general-tests"], auto_gen_config: true, - edition: "2018", + edition: "2021", cfgs: ["test"], rustlibs: [ "libenv_logger", @@ -115,15 +115,15 @@ rust_library { host_supported: true, crate_name: "env_logger", cargo_env_compat: true, - cargo_pkg_version: "0.9.0", + cargo_pkg_version: "0.10.0", srcs: ["src/lib.rs"], - edition: "2018", + edition: "2021", rustlibs: [ "liblog_rust", ], apex_available: [ "//apex_available:platform", - "//apex_available:anyapex" + "//apex_available:anyapex", ], vendor_available: true, min_sdk_version: "29", diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 266e24a..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,3 +0,0 @@ -Changes to this crate are tracked via [GitHub Releases][releases]. - -[releases]: https://github.com/env-logger-rs/env_logger/releases diff --git a/Cargo.lock.saved b/Cargo.lock.saved new file mode 100644 index 0000000..ef3b241 --- /dev/null +++ b/Cargo.lock.saved @@ -0,0 +1,254 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aho-corasick" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4f55bd91a0978cbfd91c457a164bab8b4001c833b7f323132c0a4e1922dd44e" +dependencies = [ + "memchr", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "cc" +version = "1.0.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "env_logger" +version = "0.10.0" +dependencies = [ + "humantime", + "is-terminal", + "log", + "regex", + "termcolor", +] + +[[package]] +name = "errno" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1" +dependencies = [ + "errno-dragonfly", + "libc", + "winapi", +] + +[[package]] +name = "errno-dragonfly" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "hermit-abi" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" +dependencies = [ + "libc", +] + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + +[[package]] +name = "io-lifetimes" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7d367024b3f3414d8e01f437f704f41a9f64ab36f9067fa73e526ad4c763c87" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "is-terminal" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aae5bc6e2eb41c9def29a3e0f1306382807764b9b53112030eff57435667352d" +dependencies = [ + "hermit-abi", + "io-lifetimes", + "rustix", + "windows-sys", +] + +[[package]] +name = "libc" +version = "0.2.137" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" + +[[package]] +name = "linux-raw-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f9f08d8963a6c613f4b1a78f4f4a4dbfadf8e6545b2d72861731e4858b8b47f" + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "regex" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e076559ef8e241f2ae3479e36f97bd5741c0330689e217ad51ce2c76808b868a" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" + +[[package]] +name = "rustix" +version = "0.36.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b1fbb4dfc4eb1d390c02df47760bb19a84bb80b301ecc947ab5406394d8223e" +dependencies = [ + "bitflags", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "termcolor" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" @@ -3,26 +3,75 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies +# to registry (e.g., crates.io) dependencies. # -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. [package] -edition = "2018" +edition = "2021" +rust-version = "1.60.0" name = "env_logger" -version = "0.9.0" -authors = ["The Rust Project Developers"] -include = ["src/**/*", "tests", "LICENSE-*", "README.md", "CHANGELOG.md"] -description = "A logging implementation for `log` which is configured via an environment\nvariable.\n" -documentation = "https://docs.rs/env_logger" +version = "0.10.0" +include = [ + "build.rs", + "src/**/*", + "Cargo.toml", + "LICENSE*", + "README.md", + "tests/**/*", + "benches/**/*", + "examples/**/*", +] +description = """ +A logging implementation for `log` which is configured via an environment +variable. +""" readme = "README.md" -keywords = ["logging", "log", "logger"] +keywords = [ + "logging", + "log", + "logger", +] categories = ["development-tools::debugging"] -license = "MIT/Apache-2.0" -repository = "https://github.com/env-logger-rs/env_logger/" +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-cli/env_logger/" + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "Unreleased" +replace = "{{version}}" +min = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = '\.\.\.HEAD' +replace = "...{{tag_name}}" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "ReleaseDate" +replace = "{{date}}" +min = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "<!-- next-header -->" +replace = """ +<!-- next-header --> +## [Unreleased] - ReleaseDate +""" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "<!-- next-url -->" +replace = """ +<!-- next-url --> +[Unreleased]: https://github.com/rust-cli/env_logger/compare/{{tag_name}}...HEAD""" +exactly = 1 [[test]] name = "regexp_filter" @@ -39,27 +88,42 @@ harness = false [[test]] name = "init-twice-retains-filter" harness = false -[dependencies.atty] -version = "0.2.5" -optional = true [dependencies.humantime] version = "2.0.0" optional = true +[dependencies.is-terminal] +version = "0.4.0" +optional = true + [dependencies.log] version = "0.4.8" features = ["std"] [dependencies.regex] version = "1.0.3" -features = ["std", "perf"] +features = [ + "std", + "perf", +] optional = true default-features = false [dependencies.termcolor] -version = "1.0.2" +version = "1.1.1" optional = true [features] -default = ["termcolor", "atty", "humantime", "regex"] +auto-color = [ + "dep:is-terminal", + "color", +] +color = ["dep:termcolor"] +default = [ + "auto-color", + "humantime", + "regex", +] +humantime = ["dep:humantime"] +regex = ["dep:regex"] diff --git a/Cargo.toml.orig b/Cargo.toml.orig index 29c77b3..64b9ee9 100644 --- a/Cargo.toml.orig +++ b/Cargo.toml.orig @@ -1,31 +1,54 @@ +[workspace] +members = [ + "ci" +] + [package] name = "env_logger" -edition = "2018" -version = "0.9.0" -authors = ["The Rust Project Developers"] -license = "MIT/Apache-2.0" -readme = "README.md" -repository = "https://github.com/env-logger-rs/env_logger/" -documentation = "https://docs.rs/env_logger" +version = "0.10.0" description = """ A logging implementation for `log` which is configured via an environment variable. """ +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-cli/env_logger/" categories = ["development-tools::debugging"] keywords = ["logging", "log", "logger"] -include = ["src/**/*", "tests", "LICENSE-*", "README.md", "CHANGELOG.md"] +edition = "2021" +rust-version = "1.60.0" # MSRV +include = [ + "build.rs", + "src/**/*", + "Cargo.toml", + "LICENSE*", + "README.md", + "tests/**/*", + "benches/**/*", + "examples/**/*" +] -[workspace] -members = [ - "ci" +[package.metadata.release] +pre-release-replacements = [ + {file="CHANGELOG.md", search="Unreleased", replace="{{version}}", min=1}, + {file="CHANGELOG.md", search="\\.\\.\\.HEAD", replace="...{{tag_name}}", exactly=1}, + {file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}", min=1}, + {file="CHANGELOG.md", search="<!-- next-header -->", replace="<!-- next-header -->\n## [Unreleased] - ReleaseDate\n", exactly=1}, + {file="CHANGELOG.md", search="<!-- next-url -->", replace="<!-- next-url -->\n[Unreleased]: https://github.com/rust-cli/env_logger/compare/{{tag_name}}...HEAD", exactly=1}, ] +[features] +default = ["auto-color", "humantime", "regex"] +color = ["dep:termcolor"] +auto-color = ["dep:is-terminal", "color"] +humantime = ["dep:humantime"] +regex = ["dep:regex"] + [dependencies] log = { version = "0.4.8", features = ["std"] } regex = { version = "1.0.3", optional = true, default-features=false, features=["std", "perf"] } -termcolor = { version = "1.0.2", optional = true } +termcolor = { version = "1.1.1", optional = true } humantime = { version = "2.0.0", optional = true } -atty = { version = "0.2.5", optional = true } +is-terminal = { version = "0.4.0", optional = true } [[test]] name = "regexp_filter" @@ -42,6 +65,3 @@ harness = false [[test]] name = "init-twice-retains-filter" harness = false - -[features] -default = ["termcolor", "atty", "humantime", "regex"] diff --git a/LICENSE-MIT b/LICENSE-MIT index 39d4bdb..31aa793 100644 --- a/LICENSE-MIT +++ b/LICENSE-MIT @@ -1,5 +1,3 @@ -Copyright (c) 2014 The Rust Project Developers - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the @@ -1,3 +1,7 @@ +# This project was upgraded with external_updater. +# Usage: tools/external_updater/updater.sh update rust/crates/env_logger +# For more info, check https://cs.android.com/android/platform/superproject/+/master:tools/external_updater/README.md + name: "env_logger" description: "A logging implementation for `log` which is configured via an environment variable." third_party { @@ -7,13 +11,13 @@ third_party { } url { type: ARCHIVE - value: "https://static.crates.io/crates/env_logger/env_logger-0.9.0.crate" + value: "https://static.crates.io/crates/env_logger/env_logger-0.10.0.crate" } - version: "0.9.0" + version: "0.10.0" license_type: NOTICE last_upgrade_date { - year: 2021 - month: 8 + year: 2022 + month: 12 day: 9 } } @@ -1,10 +1,8 @@ # env_logger -[![Maintenance](https://img.shields.io/badge/maintenance-actively%20maintained-brightgreen.svg)](https://github.com/env-logger-rs/env_logger) [![crates.io](https://img.shields.io/crates/v/env_logger.svg)](https://crates.io/crates/env_logger) [![Documentation](https://docs.rs/env_logger/badge.svg)](https://docs.rs/env_logger) -[![Documentation](https://img.shields.io/badge/docs-master-blue.svg)](https://env-logger-rs.github.io/env_logger/env_logger/index.html) -========== +[![Documentation](https://img.shields.io/badge/docs-main-blue.svg)](https://env-logger-rs.github.io/env_logger/env_logger/index.html) Implements a logger that can be configured via environment variables. @@ -12,7 +10,7 @@ Implements a logger that can be configured via environment variables. ### In libraries -`env_logger` makes sense when used in executables (binary projects). Libraries should use the [`log`](https://doc.rust-lang.org/log) crate instead. +`env_logger` makes sense when used in executables (binary projects). Libraries should use the [`log`](https://docs.rs/log) crate instead. ### In executables @@ -21,7 +19,7 @@ It must be added along with `log` to the project dependencies: ```toml [dependencies] log = "0.4.0" -env_logger = "0.8.4" +env_logger = "0.9.0" ``` `env_logger` must be initialized as early as possible in the project. After it's initialized, you can use the `log` macros to do actual logging. @@ -77,7 +75,7 @@ There is also a pseudo logging level, `off`, which may be specified to disable all logging for a given module or for the entire application. As with the logging levels, the letter case is not significant. -`env_logger` can be configured in other ways besides an environment variable. See [the examples](https://github.com/env-logger-rs/env_logger/tree/master/examples) for more approaches. +`env_logger` can be configured in other ways besides an environment variable. See [the examples](https://github.com/env-logger-rs/env_logger/tree/main/examples) for more approaches. ### In tests @@ -88,7 +86,7 @@ Tests can use the `env_logger` crate to see log messages generated during that t log = "0.4.0" [dev-dependencies] -env_logger = "0.8.4" +env_logger = "0.9.0" ``` ```rust diff --git a/examples/custom_default_format.rs b/examples/custom_default_format.rs new file mode 100644 index 0000000..b04eb60 --- /dev/null +++ b/examples/custom_default_format.rs @@ -0,0 +1,40 @@ +/*! +Disabling parts of the default format. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors +or `auto` to enable them: + +```no_run,shell +$ export MY_LOG_STYLE=never +``` + +If you want to control the logging output completely, see the `custom_logger` example. +*/ + +#[macro_use] +extern crate log; + +use env_logger::{Builder, Env}; + +fn init_logger() { + let env = Env::default() + .filter("MY_LOG_LEVEL") + .write_style("MY_LOG_STYLE"); + + Builder::from_env(env) + .format_level(false) + .format_timestamp_nanos() + .init(); +} + +fn main() { + init_logger(); + + info!("a log from `MyLogger`"); +} diff --git a/examples/custom_format.rs b/examples/custom_format.rs new file mode 100644 index 0000000..cc16b33 --- /dev/null +++ b/examples/custom_format.rs @@ -0,0 +1,54 @@ +/*! +Changing the default logging format. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors +or `auto` to enable them: + +```no_run,shell +$ export MY_LOG_STYLE=never +``` + +If you want to control the logging output completely, see the `custom_logger` example. +*/ + +#[cfg(all(feature = "color", feature = "humantime"))] +fn main() { + use env_logger::{fmt::Color, Builder, Env}; + + use std::io::Write; + + fn init_logger() { + let env = Env::default() + .filter("MY_LOG_LEVEL") + .write_style("MY_LOG_STYLE"); + + Builder::from_env(env) + .format(|buf, record| { + let mut style = buf.style(); + style.set_bg(Color::Yellow).set_bold(true); + + let timestamp = buf.timestamp(); + + writeln!( + buf, + "My formatted log ({}): {}", + timestamp, + style.value(record.args()) + ) + }) + .init(); + } + + init_logger(); + + log::info!("a log from `MyLogger`"); +} + +#[cfg(not(all(feature = "color", feature = "humantime")))] +fn main() {} diff --git a/examples/custom_logger.rs b/examples/custom_logger.rs new file mode 100644 index 0000000..ca3a4a9 --- /dev/null +++ b/examples/custom_logger.rs @@ -0,0 +1,62 @@ +/*! +Using `env_logger` to drive a custom logger. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +If you only want to change the way logs are formatted, look at the `custom_format` example. +*/ + +#[macro_use] +extern crate log; + +use env_logger::filter::{Builder, Filter}; + +use log::{Log, Metadata, Record, SetLoggerError}; + +const FILTER_ENV: &str = "MY_LOG_LEVEL"; + +struct MyLogger { + inner: Filter, +} + +impl MyLogger { + fn new() -> MyLogger { + let mut builder = Builder::from_env(FILTER_ENV); + + MyLogger { + inner: builder.build(), + } + } + + fn init() -> Result<(), SetLoggerError> { + let logger = Self::new(); + + log::set_max_level(logger.inner.filter()); + log::set_boxed_logger(Box::new(logger)) + } +} + +impl Log for MyLogger { + fn enabled(&self, metadata: &Metadata) -> bool { + self.inner.enabled(metadata) + } + + fn log(&self, record: &Record) { + // Check if the record is matched by the logger before logging + if self.inner.matches(record) { + println!("{} - {}", record.level(), record.args()); + } + } + + fn flush(&self) {} +} + +fn main() { + MyLogger::init().unwrap(); + + info!("a log from `MyLogger`"); +} diff --git a/examples/default.rs b/examples/default.rs new file mode 100644 index 0000000..67bb030 --- /dev/null +++ b/examples/default.rs @@ -0,0 +1,38 @@ +/*! +Using `env_logger`. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors +or `auto` to enable them: + +```no_run,shell +$ export MY_LOG_STYLE=never +``` +*/ + +#[macro_use] +extern crate log; + +use env_logger::Env; + +fn main() { + // The `Env` lets us tweak what the environment + // variables to read are and what the default + // value is if they're missing + let env = Env::default() + .filter_or("MY_LOG_LEVEL", "trace") + .write_style_or("MY_LOG_STYLE", "always"); + + env_logger::init_from_env(env); + + trace!("some trace log"); + debug!("some debug log"); + info!("some information log"); + warn!("some warning log"); + error!("some error log"); +} diff --git a/examples/direct_logger.rs b/examples/direct_logger.rs new file mode 100644 index 0000000..4d7f39d --- /dev/null +++ b/examples/direct_logger.rs @@ -0,0 +1,39 @@ +/*! +Using `env_logger::Logger` and the `log::Log` trait directly. + +This example doesn't rely on environment variables, or having a static logger installed. +*/ + +use env_logger::{Builder, WriteStyle}; + +use log::{Level, LevelFilter, Log, MetadataBuilder, Record}; + +fn record() -> Record<'static> { + let error_metadata = MetadataBuilder::new() + .target("myApp") + .level(Level::Error) + .build(); + + Record::builder() + .metadata(error_metadata) + .args(format_args!("Error!")) + .line(Some(433)) + .file(Some("app.rs")) + .module_path(Some("server")) + .build() +} + +fn main() { + let stylish_logger = Builder::new() + .filter(None, LevelFilter::Error) + .write_style(WriteStyle::Always) + .build(); + + let unstylish_logger = Builder::new() + .filter(None, LevelFilter::Error) + .write_style(WriteStyle::Never) + .build(); + + stylish_logger.log(&record()); + unstylish_logger.log(&record()); +} diff --git a/examples/filters_from_code.rs b/examples/filters_from_code.rs new file mode 100644 index 0000000..c877a44 --- /dev/null +++ b/examples/filters_from_code.rs @@ -0,0 +1,20 @@ +/*! +Specify logging filters in code instead of using an environment variable. +*/ + +#[macro_use] +extern crate log; + +use env_logger::Builder; + +use log::LevelFilter; + +fn main() { + Builder::new().filter_level(LevelFilter::max()).init(); + + trace!("some trace log"); + debug!("some debug log"); + info!("some information log"); + warn!("some warning log"); + error!("some error log"); +} diff --git a/examples/in_tests.rs b/examples/in_tests.rs new file mode 100644 index 0000000..c4487cc --- /dev/null +++ b/examples/in_tests.rs @@ -0,0 +1,54 @@ +/*! +Using `env_logger` in tests. + +Log events will be captured by `cargo` and only printed if the test fails. +You can run this example by calling: + +```text +cargo test --example in_tests +``` + +You should see the `it_does_not_work` test fail and include its log output. +*/ + +#[cfg_attr(test, macro_use)] +extern crate log; + +fn main() {} + +#[cfg(test)] +mod tests { + fn init_logger() { + let _ = env_logger::builder() + // Include all events in tests + .filter_level(log::LevelFilter::max()) + // Ensure events are captured by `cargo test` + .is_test(true) + // Ignore errors initializing the logger if tests race to configure it + .try_init(); + } + + #[test] + fn it_works() { + init_logger(); + + let a = 1; + let b = 2; + + debug!("checking whether {} + {} = 3", a, b); + + assert_eq!(3, a + b); + } + + #[test] + fn it_does_not_work() { + init_logger(); + + let a = 1; + let b = 2; + + debug!("checking whether {} + {} = 6", a, b); + + assert_eq!(6, a + b); + } +} diff --git a/examples/syslog_friendly_format.rs b/examples/syslog_friendly_format.rs new file mode 100644 index 0000000..9809ab3 --- /dev/null +++ b/examples/syslog_friendly_format.rs @@ -0,0 +1,24 @@ +use std::io::Write;
+
+fn main() {
+ match std::env::var("RUST_LOG_STYLE") {
+ Ok(s) if s == "SYSTEMD" => env_logger::builder()
+ .format(|buf, record| {
+ writeln!(
+ buf,
+ "<{}>{}: {}",
+ match record.level() {
+ log::Level::Error => 3,
+ log::Level::Warn => 4,
+ log::Level::Info => 6,
+ log::Level::Debug => 7,
+ log::Level::Trace => 7,
+ },
+ record.target(),
+ record.args()
+ )
+ })
+ .init(),
+ _ => env_logger::init(),
+ };
+}
diff --git a/src/filter/mod.rs b/src/filter/mod.rs index 9ebeab0..721dcb4 100644 --- a/src/filter/mod.rs +++ b/src/filter/mod.rs @@ -151,7 +151,7 @@ impl Filter { } if let Some(filter) = self.filter.as_ref() { - if !filter.is_match(&*record.args().to_string()) { + if !filter.is_match(&record.args().to_string()) { return false; } } @@ -762,7 +762,7 @@ mod tests { #[test] fn parse_spec_blank_level_isolated_comma_only() { // The spec should contain zero or more comma-separated string slices, - // so a comma-only string should be interpretted as two empty strings + // so a comma-only string should be interpreted as two empty strings // (which should both be treated as invalid, so ignored). let (dirs, filter) = parse_spec(","); // should be ignored assert_eq!(dirs.len(), 0); @@ -772,7 +772,7 @@ mod tests { #[test] fn parse_spec_blank_level_isolated_comma_blank() { // The spec should contain zero or more comma-separated string slices, - // so this bogus spec should be interpretted as containing one empty + // so this bogus spec should be interpreted as containing one empty // string and one blank string. Both should both be treated as // invalid, so ignored. let (dirs, filter) = parse_spec(", "); // should be ignored @@ -783,7 +783,7 @@ mod tests { #[test] fn parse_spec_blank_level_isolated_blank_comma() { // The spec should contain zero or more comma-separated string slices, - // so this bogus spec should be interpretted as containing one blank + // so this bogus spec should be interpreted as containing one blank // string and one empty string. Both should both be treated as // invalid, so ignored. let (dirs, filter) = parse_spec(" ,"); // should be ignored diff --git a/src/fmt/humantime/extern_impl.rs b/src/fmt/humantime/extern_impl.rs index 19dec1b..bdf165c 100644 --- a/src/fmt/humantime/extern_impl.rs +++ b/src/fmt/humantime/extern_impl.rs @@ -99,7 +99,7 @@ impl fmt::Debug for Timestamp { } f.debug_tuple("Timestamp") - .field(&TimestampValue(&self)) + .field(&TimestampValue(self)) .finish() } } diff --git a/src/fmt/mod.rs b/src/fmt/mod.rs index 21e0957..86c093f 100644 --- a/src/fmt/mod.rs +++ b/src/fmt/mod.rs @@ -202,9 +202,9 @@ impl Builder { } } -#[cfg(feature = "termcolor")] +#[cfg(feature = "color")] type SubtleStyle = StyledValue<'static, &'static str>; -#[cfg(not(feature = "termcolor"))] +#[cfg(not(feature = "color"))] type SubtleStyle = &'static str; /// The default format. @@ -233,7 +233,7 @@ impl<'a> DefaultFormat<'a> { } fn subtle_style(&self, text: &'static str) -> SubtleStyle { - #[cfg(feature = "termcolor")] + #[cfg(feature = "color")] { self.buf .style() @@ -242,7 +242,7 @@ impl<'a> DefaultFormat<'a> { .clone() .into_value(text) } - #[cfg(not(feature = "termcolor"))] + #[cfg(not(feature = "color"))] { text } @@ -268,11 +268,11 @@ impl<'a> DefaultFormat<'a> { } let level = { - #[cfg(feature = "termcolor")] + #[cfg(feature = "color")] { self.buf.default_styled_level(record.level()) } - #[cfg(not(feature = "termcolor"))] + #[cfg(not(feature = "color"))] { record.level() } @@ -406,7 +406,7 @@ mod tests { String::from_utf8(buf.bytes().to_vec()).expect("failed to read record") } - fn write_target<'a>(target: &'a str, fmt: DefaultFormat) -> String { + fn write_target(target: &str, fmt: DefaultFormat) -> String { write_record( Record::builder() .args(format_args!("log\nmessage")) diff --git a/src/fmt/writer/atty.rs b/src/fmt/writer/atty.rs index 343539c..1a133ee 100644 --- a/src/fmt/writer/atty.rs +++ b/src/fmt/writer/atty.rs @@ -1,24 +1,25 @@ /* This internal module contains the terminal detection implementation. -If the `atty` crate is available then we use it to detect whether we're -attached to a particular TTY. If the `atty` crate is not available we -assume we're not attached to anything. This effectively prevents styles -from being printed. +If the `auto-color` feature is enabled then we detect whether we're attached to a particular TTY. +Otherwise, assume we're not attached to anything. This effectively prevents styles from being +printed. */ -#[cfg(feature = "atty")] +#[cfg(feature = "auto-color")] mod imp { + use is_terminal::IsTerminal; + pub(in crate::fmt) fn is_stdout() -> bool { - atty::is(atty::Stream::Stdout) + std::io::stdout().is_terminal() } pub(in crate::fmt) fn is_stderr() -> bool { - atty::is(atty::Stream::Stderr) + std::io::stderr().is_terminal() } } -#[cfg(not(feature = "atty"))] +#[cfg(not(feature = "auto-color"))] mod imp { pub(in crate::fmt) fn is_stdout() -> bool { false diff --git a/src/fmt/writer/mod.rs b/src/fmt/writer/mod.rs index 5bb5353..7f4b6f9 100644 --- a/src/fmt/writer/mod.rs +++ b/src/fmt/writer/mod.rs @@ -165,6 +165,7 @@ impl Builder { } /// Whether or not to capture logs for `cargo test`. + #[allow(clippy::wrong_self_convention)] pub(crate) fn is_test(&mut self, is_test: bool) -> &mut Self { self.is_test = is_test; self @@ -193,7 +194,7 @@ impl Builder { let writer = match mem::take(&mut self.target) { WritableTarget::Stderr => BufferWriter::stderr(self.is_test, color_choice), WritableTarget::Stdout => BufferWriter::stdout(self.is_test, color_choice), - WritableTarget::Pipe(pipe) => BufferWriter::pipe(self.is_test, color_choice, pipe), + WritableTarget::Pipe(pipe) => BufferWriter::pipe(color_choice, pipe), }; Writer { diff --git a/src/fmt/writer/termcolor/extern_impl.rs b/src/fmt/writer/termcolor/extern_impl.rs index 11012fb..89c3822 100644 --- a/src/fmt/writer/termcolor/extern_impl.rs +++ b/src/fmt/writer/termcolor/extern_impl.rs @@ -71,19 +71,19 @@ impl Formatter { pub(in crate::fmt::writer) struct BufferWriter { inner: termcolor::BufferWriter, - test_target: Option<WritableTarget>, + uncolored_target: Option<WritableTarget>, } pub(in crate::fmt) struct Buffer { inner: termcolor::Buffer, - has_test_target: bool, + has_uncolored_target: bool, } impl BufferWriter { pub(in crate::fmt::writer) fn stderr(is_test: bool, write_style: WriteStyle) -> Self { BufferWriter { inner: termcolor::BufferWriter::stderr(write_style.into_color_choice()), - test_target: if is_test { + uncolored_target: if is_test { Some(WritableTarget::Stderr) } else { None @@ -94,7 +94,7 @@ impl BufferWriter { pub(in crate::fmt::writer) fn stdout(is_test: bool, write_style: WriteStyle) -> Self { BufferWriter { inner: termcolor::BufferWriter::stdout(write_style.into_color_choice()), - test_target: if is_test { + uncolored_target: if is_test { Some(WritableTarget::Stdout) } else { None @@ -103,30 +103,25 @@ impl BufferWriter { } pub(in crate::fmt::writer) fn pipe( - is_test: bool, write_style: WriteStyle, pipe: Box<Mutex<dyn io::Write + Send + 'static>>, ) -> Self { BufferWriter { - // The inner Buffer is never printed from, but it is still needed to handle coloring and other formating + // The inner Buffer is never printed from, but it is still needed to handle coloring and other formatting inner: termcolor::BufferWriter::stderr(write_style.into_color_choice()), - test_target: if is_test { - Some(WritableTarget::Pipe(pipe)) - } else { - None - }, + uncolored_target: Some(WritableTarget::Pipe(pipe)), } } pub(in crate::fmt::writer) fn buffer(&self) -> Buffer { Buffer { inner: self.inner.buffer(), - has_test_target: self.test_target.is_some(), + has_uncolored_target: self.uncolored_target.is_some(), } } pub(in crate::fmt::writer) fn print(&self, buf: &Buffer) -> io::Result<()> { - if let Some(target) = &self.test_target { + if let Some(target) = &self.uncolored_target { // This impl uses the `eprint` and `print` macros // instead of `termcolor`'s buffer. // This is so their output can be captured by `cargo test` @@ -164,7 +159,7 @@ impl Buffer { fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { // Ignore styles for test captured logs because they can't be printed - if !self.has_test_target { + if !self.has_uncolored_target { self.inner.set_color(spec) } else { Ok(()) @@ -173,7 +168,7 @@ impl Buffer { fn reset(&mut self) -> io::Result<()> { // Ignore styles for test captured logs because they can't be printed - if !self.has_test_target { + if !self.has_uncolored_target { self.inner.reset() } else { Ok(()) @@ -339,6 +334,33 @@ impl Style { self } + /// Set whether the text is dimmed. + /// + /// If `yes` is true then text will be written in a dimmer color. + /// If `yes` is false then text will be written in the default color. + /// + /// # Examples + /// + /// Create a style with dimmed text: + /// + /// ``` + /// use std::io::Write; + /// + /// let mut builder = env_logger::Builder::new(); + /// + /// builder.format(|buf, record| { + /// let mut style = buf.style(); + /// + /// style.set_dimmed(true); + /// + /// writeln!(buf, "{}", style.value(record.args())) + /// }); + /// ``` + pub fn set_dimmed(&mut self, yes: bool) -> &mut Style { + self.spec.set_dimmed(yes); + self + } + /// Set the background color. /// /// # Examples @@ -453,7 +475,7 @@ impl_styled_value_fmt!( fmt::LowerExp ); -// The `Color` type is copied from https://github.com/BurntSushi/ripgrep/tree/master/termcolor +// The `Color` type is copied from https://github.com/BurntSushi/termcolor /// The set of available colors for the terminal foreground/background. /// diff --git a/src/fmt/writer/termcolor/mod.rs b/src/fmt/writer/termcolor/mod.rs index f3e6768..20f0197 100644 --- a/src/fmt/writer/termcolor/mod.rs +++ b/src/fmt/writer/termcolor/mod.rs @@ -5,8 +5,8 @@ Its public API is available when the `termcolor` crate is available. The terminal printing is shimmed when the `termcolor` crate is not available. */ -#[cfg_attr(feature = "termcolor", path = "extern_impl.rs")] -#[cfg_attr(not(feature = "termcolor"), path = "shim_impl.rs")] +#[cfg_attr(feature = "color", path = "extern_impl.rs")] +#[cfg_attr(not(feature = "color"), path = "shim_impl.rs")] mod imp; pub(in crate::fmt) use self::imp::*; diff --git a/src/fmt/writer/termcolor/shim_impl.rs b/src/fmt/writer/termcolor/shim_impl.rs index bfc31d0..0705770 100644 --- a/src/fmt/writer/termcolor/shim_impl.rs +++ b/src/fmt/writer/termcolor/shim_impl.rs @@ -24,7 +24,6 @@ impl BufferWriter { } pub(in crate::fmt::writer) fn pipe( - _is_test: bool, _write_style: WriteStyle, pipe: Box<Mutex<dyn io::Write + Send + 'static>>, ) -> Self { @@ -1,10 +1,6 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. @@ -101,13 +97,13 @@ //! ``` //! //! The log target is typically equal to the path of the module the message -//! in question originated from, though it can be overriden. +//! in question originated from, though it can be overridden. //! //! The path is rooted in the name of the crate it was compiled for, so if //! your program is in a file called, for example, `hello.rs`, the path would //! simply be be `hello`. //! -//! Furthermore, the the log can be filtered using prefix-search based on the +//! Furthermore, the log can be filtered using prefix-search based on the //! specified log target. A value of, for example, `RUST_LOG=example`, would //! match all of the messages with targets: //! @@ -676,7 +672,7 @@ impl Builder { /// /// # Examples /// - /// Only include messages for info and above for logs in `path::to::module`: + /// Only include messages for info and above for logs globally: /// /// ``` /// use env_logger::Builder; @@ -911,7 +907,7 @@ impl Log for Logger { fn log(&self, record: &Record) { if self.matches(record) { // Log records are written to a thread-local buffer before being printed - // to the terminal. We clear these buffers afterwards, but they aren't shrinked + // to the terminal. We clear these buffers afterwards, but they aren't shrunk // so will always at least have capacity for the largest log record formatted // on that thread. // @@ -1172,7 +1168,7 @@ pub fn init() { /// ``` /// use env_logger::{Builder, Env}; /// -/// # fn run() -> Result<(), Box<::std::error::Error>> { +/// # fn run() -> Result<(), Box<dyn ::std::error::Error>> { /// let env = Env::new().filter("MY_LOG").write_style("MY_LOG_STYLE"); /// /// env_logger::try_init_from_env(env)?; |