├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── ci ├── build.bash ├── common.bash ├── set_rust_version.bash └── test.bash ├── examples ├── log.rs ├── with_builder_1.rs ├── with_custom_env.rs └── with_try_init.rs ├── readme-example.png └── src └── lib.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | rustfmt: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - name: Checkout sources 9 | uses: actions/checkout@v2 10 | 11 | - name: Install stable toolchain with rustfmt available 12 | uses: actions-rs/toolchain@v1 13 | with: 14 | toolchain: stable 15 | override: true 16 | components: rustfmt 17 | 18 | - run: cargo fmt -- --check 19 | 20 | clippy: 21 | runs-on: ubuntu-latest 22 | steps: 23 | - uses: actions/checkout@v1 24 | - uses: actions-rs/toolchain@v1 25 | with: 26 | toolchain: stable 27 | components: clippy 28 | override: true 29 | - uses: actions-rs/clippy-check@v1 30 | with: 31 | token: ${{ secrets.GITHUB_TOKEN }} 32 | - run: cargo clippy -- -D warnings 33 | 34 | install-cross: 35 | runs-on: ubuntu-latest 36 | steps: 37 | - uses: actions/checkout@v1 38 | with: 39 | fetch-depth: 50 40 | - uses: XAMPPRocky/get-github-release@v1 41 | id: cross 42 | with: 43 | owner: rust-embedded 44 | repo: cross 45 | matches: ${{ matrix.platform }} 46 | token: ${{ secrets.GITHUB_TOKEN }} 47 | - uses: actions/upload-artifact@v1 48 | with: 49 | name: cross-${{ matrix.platform }} 50 | path: ${{ steps.cross.outputs.install_path }} 51 | strategy: 52 | matrix: 53 | platform: [linux-musl] 54 | 55 | windows: 56 | runs-on: windows-latest 57 | # Windows technically doesn't need this, but if we don't block windows on it 58 | # some of the windows jobs could fill up the concurrent job queue before 59 | # one of the install-cross jobs has started, so this makes sure all 60 | # artifacts are downloaded first. 61 | needs: install-cross 62 | steps: 63 | - uses: actions/checkout@v2 64 | with: 65 | fetch-depth: 50 66 | - run: ci/set_rust_version.bash ${{ matrix.channel }} ${{ matrix.target }} 67 | shell: bash 68 | - run: ci/build.bash cargo ${{ matrix.target }} 69 | shell: bash 70 | - run: ci/test.bash cargo ${{ matrix.target }} 71 | shell: bash 72 | 73 | strategy: 74 | fail-fast: true 75 | matrix: 76 | channel: [stable, beta, nightly] 77 | target: 78 | # MSVC 79 | - i686-pc-windows-msvc 80 | - x86_64-pc-windows-msvc 81 | # GNU: You typically only need to test Windows GNU if you're 82 | # specifically targetting it, and it can cause issues with some 83 | # dependencies if you're not so it's disabled by self. 84 | # - i686-pc-windows-gnu 85 | # - x86_64-pc-windows-gnu 86 | 87 | macos: 88 | runs-on: macos-latest 89 | strategy: 90 | fail-fast: true 91 | matrix: 92 | channel: [stable, beta, nightly] 93 | target: 94 | - x86_64-apple-darwin 95 | ### Disable running tests on M1 target, not currently working 96 | ### 97 | #- aarch64-apple-darwin 98 | steps: 99 | - name: Setup | Checkout 100 | uses: actions/checkout@v2 101 | 102 | - name: Setup | Rust 103 | uses: actions-rs/toolchain@v1 104 | with: 105 | toolchain: stable 106 | override: true 107 | profile: minimal 108 | target: ${{ matrix.target }} 109 | 110 | - run: ci/set_rust_version.bash ${{ matrix.channel }} ${{ matrix.target }} 111 | 112 | - name: Test 113 | uses: actions-rs/cargo@v1 114 | with: 115 | command: test 116 | args: --target ${{ matrix.target }} 117 | 118 | linux: 119 | runs-on: ubuntu-latest 120 | needs: install-cross 121 | steps: 122 | - uses: actions/checkout@v2 123 | with: 124 | fetch-depth: 50 125 | 126 | - name: Download Cross 127 | uses: actions/download-artifact@v1 128 | with: 129 | name: cross-linux-musl 130 | path: /tmp/ 131 | - run: chmod +x /tmp/cross 132 | - run: ci/set_rust_version.bash ${{ matrix.channel }} ${{ matrix.target }} 133 | - run: ci/build.bash /tmp/cross ${{ matrix.target }} 134 | # These targets have issues with being tested so they are disabled 135 | # by default. You can try disabling to see if they work for 136 | # your project. 137 | - run: ci/test.bash /tmp/cross ${{ matrix.target }} 138 | if: | 139 | !contains(matrix.target, 'android') && 140 | !contains(matrix.target, 'bsd') && 141 | !contains(matrix.target, 'solaris') && 142 | matrix.target != 'armv5te-unknown-linux-musleabi' && 143 | matrix.target != 'sparc64-unknown-linux-gnu' 144 | 145 | strategy: 146 | fail-fast: true 147 | matrix: 148 | channel: [stable, beta, nightly] 149 | target: 150 | # WASM, off by default as most rust projects aren't compatible yet. 151 | # - wasm32-unknown-emscripten 152 | # Linux 153 | - aarch64-unknown-linux-gnu 154 | - aarch64-unknown-linux-musl 155 | - arm-unknown-linux-gnueabi 156 | - arm-unknown-linux-gnueabihf 157 | - armv7-unknown-linux-gnueabihf 158 | - i686-unknown-linux-musl 159 | - powerpc64le-unknown-linux-gnu 160 | - x86_64-unknown-linux-musl 161 | # - i686-unknown-linux-gnu 162 | # - mips-unknown-linux-gnu 163 | # - mips64-unknown-linux-gnuabi64 164 | # - mips64el-unknown-linux-gnuabi64 165 | # - mipsel-unknown-linux-gnu 166 | # - powerpc-unknown-linux-gnu 167 | # - powerpc64-unknown-linux-gnu 168 | # - s390x-unknown-linux-gnu 169 | # - x86_64-unknown-linux-gnu 170 | ## Android 171 | # - aarch64-linux-android 172 | # - arm-linux-androideabi 173 | # - armv7-linux-androideabi 174 | # - i686-linux-android 175 | # - x86_64-linux-android 176 | ## *BSD 177 | # The FreeBSD targets can have issues linking so they are disabled 178 | # by default. 179 | # - i686-unknown-freebsd 180 | # - x86_64-unknown-freebsd 181 | # - x86_64-unknown-netbsd 182 | ## Solaris 183 | # - sparcv9-sun-solaris 184 | ## Bare Metal 185 | # These are no-std embedded targets, so they will only build if your 186 | # crate is `no_std` compatible. 187 | # - thumbv6m-none-eabi 188 | # - thumbv7em-none-eabi 189 | # - thumbv7em-none-eabihf 190 | # - thumbv7m-none-eabi 191 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pretty_env_logger" 3 | version = "0.5.0" # don't forget to update html_root_url 4 | description = "a visually pretty env_logger" 5 | repository = "https://github.com/seanmonstar/pretty-env-logger" 6 | authors = ["Sean McArthur "] 7 | license = "MIT/Apache-2.0" 8 | categories = ["development-tools::debugging"] 9 | keywords = ["log", "logger", "logging"] 10 | readme = "README.md" 11 | 12 | include = [ 13 | "Cargo.toml", 14 | "LICENSE-APACHE", 15 | "LICENSE-MIT", 16 | "src/**/*" 17 | ] 18 | 19 | [dependencies] 20 | env_logger = "0.10" 21 | log = "0.4" 22 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Sean McArthur 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pretty-env-logger 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/pretty_env_logger.svg)](https://crates.io/crates/pretty_env_logger) 4 | [![Docs](https://docs.rs/pretty_env_logger/badge.svg)](https://docs.rs/pretty_env_logger) 5 | [![MIT/APACHE-2.0](https://img.shields.io/crates/l/pretty_env_logger.svg)](https://crates.io/crates/pretty_env_logger) 6 | [![Travis CI](https://travis-ci.org/seanmonstar/pretty-env-logger.svg?branch=master)](https://travis-ci.org/seanmonstar/pretty-env-logger) 7 | 8 | A simple logger built on top of [env_logger](https://docs.rs/env_logger). 9 | It is configured via an environment variable and writes to standard 10 | error with nice colored output for log levels. 11 | 12 | ![example output](readme-example.png) 13 | 14 | ## Usage 15 | 16 | Add the dependency to your `Cargo.toml`: 17 | 18 | ```toml 19 | [dependencies] 20 | log = "0.4" 21 | pretty_env_logger = "0.4" 22 | ``` 23 | 24 | Add some usage to your application: 25 | 26 | ```rust 27 | extern crate pretty_env_logger; 28 | #[macro_use] extern crate log; 29 | 30 | fn main() { 31 | pretty_env_logger::init(); 32 | info!("such information"); 33 | warn!("o_O"); 34 | error!("much error"); 35 | } 36 | ``` 37 | 38 | Then run your app with the environmental variable set: 39 | 40 | ``` 41 | RUST_LOG=trace cargo run 42 | ``` 43 | 44 | ## License 45 | 46 | Licensed under either of 47 | 48 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://apache.org/licenses/LICENSE-2.0) 49 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 50 | 51 | -------------------------------------------------------------------------------- /ci/build.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Script for building your rust projects. 3 | set -e 4 | 5 | source ci/common.bash 6 | 7 | # $1 {path} = Path to cross/cargo executable 8 | CROSS=$1 9 | # $1 {string} = e.g. x86_64-pc-windows-msvc 10 | TARGET_TRIPLE=$2 11 | # $3 {boolean} = Are we building for deployment? 12 | RELEASE_BUILD=$3 13 | 14 | required_arg $CROSS 'CROSS' 15 | required_arg $TARGET_TRIPLE '' 16 | 17 | if [ -z "$RELEASE_BUILD" ]; then 18 | $CROSS build --target $TARGET_TRIPLE 19 | $CROSS build --target $TARGET_TRIPLE --all-features 20 | else 21 | $CROSS build --target $TARGET_TRIPLE --all-features --release 22 | fi 23 | 24 | -------------------------------------------------------------------------------- /ci/common.bash: -------------------------------------------------------------------------------- 1 | required_arg() { 2 | if [ -z "$1" ]; then 3 | echo "Required argument $2 missing" 4 | exit 1 5 | fi 6 | } 7 | -------------------------------------------------------------------------------- /ci/set_rust_version.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | rustup default $1 4 | rustup target add $2 5 | -------------------------------------------------------------------------------- /ci/test.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Script for building your rust projects. 3 | set -e 4 | 5 | source ci/common.bash 6 | 7 | # $1 {path} = Path to cross/cargo executable 8 | CROSS=$1 9 | # $1 {string} = 10 | TARGET_TRIPLE=$2 11 | 12 | required_arg $CROSS 'CROSS' 13 | required_arg $TARGET_TRIPLE '' 14 | 15 | $CROSS test --target $TARGET_TRIPLE 16 | $CROSS test --target $TARGET_TRIPLE --all-features 17 | -------------------------------------------------------------------------------- /examples/log.rs: -------------------------------------------------------------------------------- 1 | extern crate pretty_env_logger; 2 | #[macro_use] 3 | extern crate log; 4 | 5 | mod nested { 6 | pub fn deep() { 7 | trace!("one level deep!"); 8 | } 9 | } 10 | 11 | fn main() { 12 | pretty_env_logger::init(); 13 | 14 | if !log_enabled!(log::Level::Trace) { 15 | eprintln!("To see the full demo, try setting `RUST_LOG=log=trace`."); 16 | return; 17 | } 18 | 19 | self::nested::deep(); 20 | debug!("deboogging"); 21 | info!("such information"); 22 | warn!("o_O"); 23 | error!("boom"); 24 | } 25 | -------------------------------------------------------------------------------- /examples/with_builder_1.rs: -------------------------------------------------------------------------------- 1 | extern crate env_logger; 2 | extern crate pretty_env_logger; 3 | #[macro_use] 4 | extern crate log; 5 | 6 | use env_logger::Target; 7 | 8 | mod one { 9 | pub fn deep() { 10 | trace!("one level deep!"); 11 | trace!("one level deep!"); 12 | } 13 | } 14 | 15 | fn main() { 16 | pretty_env_logger::formatted_builder() 17 | //let's just set some random stuff.. for more see 18 | //https://docs.rs/env_logger/0.5.0-rc.1/env_logger/struct.Builder.html 19 | .target(Target::Stdout) 20 | .parse_filters("with_builder_1=trace") 21 | .init(); 22 | 23 | info!("such information"); 24 | info!("such information"); 25 | warn!("o_O"); 26 | warn!("o_O"); 27 | error!("boom"); 28 | error!("boom"); 29 | debug!("deboogging"); 30 | debug!("deboogging"); 31 | self::one::deep(); 32 | } 33 | -------------------------------------------------------------------------------- /examples/with_custom_env.rs: -------------------------------------------------------------------------------- 1 | extern crate pretty_env_logger; 2 | #[macro_use] 3 | extern crate log; 4 | 5 | use std::env; 6 | 7 | mod one { 8 | pub fn deep() { 9 | trace!("one level deep!"); 10 | trace!("one level deep!"); 11 | } 12 | } 13 | 14 | fn main() { 15 | env::set_var("RUST_APP_LOG", "trace"); 16 | 17 | pretty_env_logger::init_custom_env("RUST_APP_LOG"); 18 | 19 | info!("such information"); 20 | info!("such information"); 21 | warn!("o_O"); 22 | warn!("o_O"); 23 | error!("boom"); 24 | error!("boom"); 25 | debug!("deboogging"); 26 | debug!("deboogging"); 27 | self::one::deep(); 28 | 29 | env::remove_var("RUST_APP_LOG"); 30 | } 31 | -------------------------------------------------------------------------------- /examples/with_try_init.rs: -------------------------------------------------------------------------------- 1 | extern crate pretty_env_logger; 2 | #[macro_use] 3 | extern crate log; 4 | 5 | mod one { 6 | pub fn deep() { 7 | trace!("one level deep!"); 8 | } 9 | } 10 | 11 | fn main() { 12 | if let Err(e) = pretty_env_logger::try_init() { 13 | eprintln!("Some custom msg {}", e); 14 | panic!("error!") // or whatever 15 | }; 16 | 17 | info!("such information"); 18 | warn!("o_O"); 19 | error!("boom"); 20 | debug!("deboogging"); 21 | self::one::deep(); 22 | } 23 | -------------------------------------------------------------------------------- /readme-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seanmonstar/pretty-env-logger/0e238400e18649415dc710c025e99c009a1bb744/readme-example.png -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(test, deny(warnings))] 2 | #![deny(missing_docs)] 3 | #![doc(html_root_url = "https://docs.rs/pretty_env_logger/0.5.0")] 4 | 5 | //! A logger configured via an environment variable which writes to standard 6 | //! error with nice colored output for log levels. 7 | //! 8 | //! ## Example 9 | //! 10 | //! ``` 11 | //! extern crate pretty_env_logger; 12 | //! #[macro_use] extern crate log; 13 | //! 14 | //! fn main() { 15 | //! pretty_env_logger::init(); 16 | //! 17 | //! trace!("a trace example"); 18 | //! debug!("deboogging"); 19 | //! info!("such information"); 20 | //! warn!("o_O"); 21 | //! error!("boom"); 22 | //! } 23 | //! ``` 24 | //! 25 | //! Run the program with the environment variable `RUST_LOG=trace`. 26 | //! 27 | //! ## Defaults 28 | //! 29 | //! The defaults can be setup by calling `init()` or `try_init()` at the start 30 | //! of the program. 31 | //! 32 | //! ## Enable logging 33 | //! 34 | //! This crate uses [env_logger][] internally, so the same ways of enabling 35 | //! logs through an environment variable are supported. 36 | //! 37 | //! [env_logger]: https://docs.rs/env_logger 38 | 39 | #[doc(hidden)] 40 | pub extern crate env_logger; 41 | 42 | extern crate log; 43 | 44 | use std::fmt; 45 | use std::sync::atomic::{AtomicUsize, Ordering}; 46 | 47 | use env_logger::{ 48 | fmt::{Color, Style, StyledValue}, 49 | Builder, 50 | }; 51 | use log::Level; 52 | 53 | /// Initializes the global logger with a pretty env logger. 54 | /// 55 | /// This should be called early in the execution of a Rust program, and the 56 | /// global logger may only be initialized once. Future initialization attempts 57 | /// will return an error. 58 | /// 59 | /// # Panics 60 | /// 61 | /// This function fails to set the global logger if one has already been set. 62 | pub fn init() { 63 | try_init().unwrap(); 64 | } 65 | 66 | /// Initializes the global logger with a timed pretty env logger. 67 | /// 68 | /// This should be called early in the execution of a Rust program, and the 69 | /// global logger may only be initialized once. Future initialization attempts 70 | /// will return an error. 71 | /// 72 | /// # Panics 73 | /// 74 | /// This function fails to set the global logger if one has already been set. 75 | pub fn init_timed() { 76 | try_init_timed().unwrap(); 77 | } 78 | 79 | /// Initializes the global logger with a pretty env logger. 80 | /// 81 | /// This should be called early in the execution of a Rust program, and the 82 | /// global logger may only be initialized once. Future initialization attempts 83 | /// will return an error. 84 | /// 85 | /// # Errors 86 | /// 87 | /// This function fails to set the global logger if one has already been set. 88 | pub fn try_init() -> Result<(), log::SetLoggerError> { 89 | try_init_custom_env("RUST_LOG") 90 | } 91 | 92 | /// Initializes the global logger with a timed pretty env logger. 93 | /// 94 | /// This should be called early in the execution of a Rust program, and the 95 | /// global logger may only be initialized once. Future initialization attempts 96 | /// will return an error. 97 | /// 98 | /// # Errors 99 | /// 100 | /// This function fails to set the global logger if one has already been set. 101 | pub fn try_init_timed() -> Result<(), log::SetLoggerError> { 102 | try_init_timed_custom_env("RUST_LOG") 103 | } 104 | 105 | /// Initialized the global logger with a pretty env logger, with a custom variable name. 106 | /// 107 | /// This should be called early in the execution of a Rust program, and the 108 | /// global logger may only be initialized once. Future initialization attempts 109 | /// will return an error. 110 | /// 111 | /// # Panics 112 | /// 113 | /// This function fails to set the global logger if one has already been set. 114 | pub fn init_custom_env(environment_variable_name: &str) { 115 | try_init_custom_env(environment_variable_name).unwrap(); 116 | } 117 | 118 | /// Initialized the global logger with a pretty env logger, with a custom variable name. 119 | /// 120 | /// This should be called early in the execution of a Rust program, and the 121 | /// global logger may only be initialized once. Future initialization attempts 122 | /// will return an error. 123 | /// 124 | /// # Errors 125 | /// 126 | /// This function fails to set the global logger if one has already been set. 127 | pub fn try_init_custom_env(environment_variable_name: &str) -> Result<(), log::SetLoggerError> { 128 | let mut builder = formatted_builder(); 129 | 130 | if let Ok(s) = ::std::env::var(environment_variable_name) { 131 | builder.parse_filters(&s); 132 | } 133 | 134 | builder.try_init() 135 | } 136 | 137 | /// Initialized the global logger with a timed pretty env logger, with a custom variable name. 138 | /// 139 | /// This should be called early in the execution of a Rust program, and the 140 | /// global logger may only be initialized once. Future initialization attempts 141 | /// will return an error. 142 | /// 143 | /// # Errors 144 | /// 145 | /// This function fails to set the global logger if one has already been set. 146 | pub fn try_init_timed_custom_env( 147 | environment_variable_name: &str, 148 | ) -> Result<(), log::SetLoggerError> { 149 | let mut builder = formatted_timed_builder(); 150 | 151 | if let Ok(s) = ::std::env::var(environment_variable_name) { 152 | builder.parse_filters(&s); 153 | } 154 | 155 | builder.try_init() 156 | } 157 | 158 | /// Returns a `env_logger::Builder` for further customization. 159 | /// 160 | /// This method will return a colored and formatted `env_logger::Builder` 161 | /// for further customization. Refer to env_logger::Build crate documentation 162 | /// for further details and usage. 163 | pub fn formatted_builder() -> Builder { 164 | let mut builder = Builder::new(); 165 | 166 | builder.format(|f, record| { 167 | use std::io::Write; 168 | 169 | let target = record.target(); 170 | let max_width = max_target_width(target); 171 | 172 | let mut style = f.style(); 173 | let level = colored_level(&mut style, record.level()); 174 | 175 | let mut style = f.style(); 176 | let target = style.set_bold(true).value(Padded { 177 | value: target, 178 | width: max_width, 179 | }); 180 | 181 | writeln!(f, " {} {} > {}", level, target, record.args(),) 182 | }); 183 | 184 | builder 185 | } 186 | 187 | /// Returns a `env_logger::Builder` for further customization. 188 | /// 189 | /// This method will return a colored and time formatted `env_logger::Builder` 190 | /// for further customization. Refer to env_logger::Build crate documentation 191 | /// for further details and usage. 192 | pub fn formatted_timed_builder() -> Builder { 193 | let mut builder = Builder::new(); 194 | 195 | builder.format(|f, record| { 196 | use std::io::Write; 197 | let target = record.target(); 198 | let max_width = max_target_width(target); 199 | 200 | let mut style = f.style(); 201 | let level = colored_level(&mut style, record.level()); 202 | 203 | let mut style = f.style(); 204 | let target = style.set_bold(true).value(Padded { 205 | value: target, 206 | width: max_width, 207 | }); 208 | 209 | let time = f.timestamp_millis(); 210 | 211 | writeln!(f, " {} {} {} > {}", time, level, target, record.args(),) 212 | }); 213 | 214 | builder 215 | } 216 | 217 | struct Padded { 218 | value: T, 219 | width: usize, 220 | } 221 | 222 | impl fmt::Display for Padded { 223 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 224 | write!(f, "{: usize { 231 | let max_width = MAX_MODULE_WIDTH.load(Ordering::Relaxed); 232 | if max_width < target.len() { 233 | MAX_MODULE_WIDTH.store(target.len(), Ordering::Relaxed); 234 | target.len() 235 | } else { 236 | max_width 237 | } 238 | } 239 | 240 | fn colored_level<'a>(style: &'a mut Style, level: Level) -> StyledValue<'a, &'static str> { 241 | match level { 242 | Level::Trace => style.set_color(Color::Magenta).value("TRACE"), 243 | Level::Debug => style.set_color(Color::Blue).value("DEBUG"), 244 | Level::Info => style.set_color(Color::Green).value("INFO "), 245 | Level::Warn => style.set_color(Color::Yellow).value("WARN "), 246 | Level::Error => style.set_color(Color::Red).value("ERROR"), 247 | } 248 | } 249 | --------------------------------------------------------------------------------