systemd-journal-logger-2.2.0/.cargo_vcs_info.json0000644000000001360000000000100154520ustar { "git": { "sha1": "2076d1a9cb2c5bef7f4f11c32269d2dd1c061dd5" }, "path_in_vcs": "" }systemd-journal-logger-2.2.0/.github/dependabot.yml000064400000000000000000000003731046102023000204350ustar 00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: monthly assignees: [swsnr] - package-ecosystem: "cargo" directory: "/" schedule: interval: monthly assignees: [swsnr] systemd-journal-logger-2.2.0/.github/workflows/test.yml000064400000000000000000000026001046102023000213370ustar 00000000000000name: Test on: push: # Don't build tags; that's redundant with pushes to main normally. tags-ignore: "*" # Only build main, for all other branches rely on pull requests. This # avoids duplicate builds for pull requests. branches: main # Don't build for trivial changes paths-ignore: - "*.md" - "LICENSE*" pull_request: jobs: test: runs-on: ubuntu-latest strategy: matrix: # Test against MRSV and stable rust: ["1.66.0", "stable"] steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: components: clippy,rustfmt toolchain: ${{ matrix.rust }} - run: cargo build --all-targets --locked - run: cargo clippy --all-targets --locked # Run clippy only on stable target; we don't need lints from old Rust # versions. if: "${{ matrix.rust == 'stable' }}" - run: cargo test --locked - run: cargo doc - run: cargo fmt -- --check # Run fmt check only on stable rust, as our reference. if: "${{ matrix.rust == 'stable' }}" cargo-deny: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: EmbarkStudios/cargo-deny-action@v2 semver-checks: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: obi1kenobi/cargo-semver-checks-action@v2 systemd-journal-logger-2.2.0/.gitignore000064400000000000000000000000101046102023000162210ustar 00000000000000/target systemd-journal-logger-2.2.0/CHANGELOG.md000064400000000000000000000143501046102023000160560ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Run [`cargo-release`][cr] to publish a release. [cr]: https://github.com/crate-ci/cargo-release/ ## [Unreleased] ## [2.2.0] – 2024-10-17 ### Changed - Use `kv` instead of `unstable_kv` of log. ## [2.1.1] – 2023-11-15 ### Changed - Decrease MSRV to 1.66, as actually required (see [GH-26]). [GH-26]: https://github.com/swsnr/systemd-journal-logger.rs/pull/26 ## [2.1.0] – 2023-10-19 ### Changed - Depend on rustix instead of libc to get rid of unsafe code (see [GH-24]). [GH-24]: https://github.com/swsnr/systemd-journal-logger.rs/pull/24 ## [2.0.0] – 2023-10-01 ### Added - `JournalLog::new` as default entry point. - Check whether journald listens when constructing a `JournalLog`. ### Changed - Remove `libsystemd` dependency, and directly implement journal access. - `JournalLog::empty` now returns `std::io::Result`. - `JournalLog` should use a lot less allocations on the hot path; in particular all fields are formatted into a single message buffer. - `JournalLog` no longer has type parameters; extra fields are now pre-formatted upon construction. - `JournalLog` no longer panics when sending a log record to journald fails; instead it silently discards the error. - `current_exe_identifier` now returns `Option` instead of `Result`. - Bump MSRV to `1.71.0`. ### Removed - `JournalLog::default`, since instantiation is now fallible. - `escape_journal_key`, because the logger handles this internally. ## [1.0.0] – 2023-04-29 ### Added - Add `JournalLog::default`, and new setters for extra fields and the syslog identifier (see [GH-17]). - Add `with_syslog_identifier` to override the syslog identifier (see [GH-16] and [GH-17]). ### Changed - Cache the syslog identifier instead of computing it for every log message (see [GH-16] and [GH-17]). ### Removed - Static `LOG` instance. Always create your own `JournalLog` instance now (see [GH-17]). - `init` and `init_with_extra_fields`. Create your own `JournalLog` instance now, and call `install` (see [GH-17]). [GH-16]: https://github.com/swsnr/systemd-journal-logger.rs/issues/16 [GH-17]: https://github.com/swsnr/systemd-journal-logger.rs/pull/17 ## [0.7.0] – 2022-12-23 ### Changed - Bump `libsystemd` dependency to `0.6.0` ## [0.6.0] – 2022-12-02 ### Changed - Bump MRSV to 1.56.0 (see [GH-11]). - Update Github URL to . [GH-11]: https://github.com/swsnr/systemd-journal-logger.rs/pull/11 ## [0.5.1] – 2022-10-15 ### Changed - Move repository, issues, etc. back to . ## [0.5.0] – 2022-01-28 ### Changed - Move repository, issues, etc. to . - Update to libsystemd 0.5.0. ## [0.4.1] – 2021-11-20 ### Changed - Bump libsystemd to `0.4.1` to support socket reuse and fix memfd leak. ## [0.4.0] – 2021-10-28 ### Changed - Update to `libsystemd` 0.4.0, and reexport `connected_to_journal()` from that crate. ### Removed - Dependencies on `libc` and `nix`. ## [0.3.1] – 2021-10-06 ### Fixed - Compile on arm7 targets (see [GH-7]). [GH-7]: https://github.com/swsnr/systemd-journal-logger.rs/pull/7 ## [0.3.0] – 2021-06-07 ### Added - Add `JournalLog::with_extra_fields` and `init_with_extra_fields` to add custom fields to every log entry (see [GH-3]). - Add new `journal_send` to send an individual log record directly to the systemd journal. - Add new `connected_to_journal` function to check for a direct connection to the systemd log in order to automatically upgrade to journal logging in systemd services (see [GH-5]). - Add record key values as custom journal fields (see [GH-1]). ### Changed - Do not silently ignore journal errors; instead panic if the logger fails to send a message to the systemd journal. - Use `CODE_MODULE` field for the Rust module path, for compatibility with the `slog-journal` and `systemd` crates. [GH-1]: https://github.com/swsnr/systemd-journal-logger.rs/pull/1 [GH-3]: https://github.com/swsnr/systemd-journal-logger.rs/pull/3 [GH-5]: https://github.com/swsnr/systemd-journal-logger.rs/pull/5 ## [0.2.0] – 2021-06-01 ### Fixed - Multiline messages are no longer lost (see [GH-2]), following an update of [libsystemd] (see [libsystemd GH-70] and [libsystemd GH-72]). [GH-2]: https://github.com/swsnr/systemd-journal-logger.rs/pull/2 [libsystemd]: https://github.com/lucab/libsystemd-rs [libsystemd GH-70]: https://github.com/lucab/libsystemd-rs/issues/70 [libsystemd GH-72]: https://github.com/lucab/libsystemd-rs/pull/72 ## [0.1.0] – 2021-05-28 (yanked) Initial release with `systemd_journal_logger::LOG` and `systemd_journal_logger::init`. Do **not use** this version; it looses multiline messages and has been yanked from crates.io. [Unreleased]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v2.2.0...HEAD [2.2.0]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v2.1.1...v2.2.0 [2.1.1]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v2.1.0...v2.1.1 [2.1.0]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v2.0.0...v2.1.0 [2.0.0]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v1.0.0...v2.0.0 [1.0.0]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v0.7.0...v1.0.0 [0.7.0]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v0.6.0...v0.7.0 [0.6.0]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v0.5.1...v0.6.0 [0.5.1]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v0.5.0...v0.5.1 [0.5.0]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v0.4.1...v0.5.0 [0.4.1]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v0.4.0...v0.4.1 [0.4.0]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v0.3.1...v0.4.0 [0.3.1]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v0.3.0...v0.3.1 [0.3.0]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/swsnr/systemd-journal-logger.rs/compare/v0.1.0...v0.2.0 [0.1.0]: https://github.com/swsnr/systemd-journal-logger.rs/releases/tag/v0.1.0 systemd-journal-logger-2.2.0/Cargo.lock0000644000000325730000000000100134370ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bitflags" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "bstr" version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40723b8fb387abc38f4f4a37c09073622e41dd12327033091ef8950659e6dc0c" dependencies = [ "memchr", "regex-automata", "serde", ] [[package]] name = "byteorder" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "console" version = "0.15.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" dependencies = [ "encode_unicode", "lazy_static", "libc", "windows-sys", ] [[package]] name = "encode_unicode" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" [[package]] name = "erased-serde" version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24e2389d65ab4fab27dc2a5de7b191e1f6617d1f1c8855c0dc569c94a4cbb18d" dependencies = [ "serde", "typeid", ] [[package]] name = "errno" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" dependencies = [ "libc", "windows-sys", ] [[package]] name = "getrandom" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", "wasi", ] [[package]] name = "itoa" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" version = "0.2.158" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" [[package]] name = "linux-raw-sys" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "log" version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" dependencies = [ "value-bag", ] [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "ppv-lite86" version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" dependencies = [ "zerocopy", ] [[package]] name = "proc-macro2" version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] [[package]] name = "rand" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", "rand_chacha", "rand_core", ] [[package]] name = "rand_chacha" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", "rand_core", ] [[package]] name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ "getrandom", ] [[package]] name = "regex-automata" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" [[package]] name = "retry" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9166d72162de3575f950507683fac47e30f6f2c3836b71b7fbc61aa517c9c5f4" dependencies = [ "rand", ] [[package]] name = "rustix" version = "0.38.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8acb788b847c24f28525660c4d7758620a7210875711f79e7f663cc152726811" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "ryu" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" [[package]] name = "serde" version = "1.0.210" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.210" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_fmt" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d4ddca14104cd60529e8c7f7ba71a2c8acd8f7f5cfcdc2faf97eeb7c3010a4" dependencies = [ "serde", ] [[package]] name = "serde_json" version = "1.0.128" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ff5456707a1de34e7e37f2a6fd3d3f808c318259cbd01ab6377795054b483d8" dependencies = [ "itoa", "memchr", "ryu", "serde", ] [[package]] name = "similar" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1de1d4f81173b03af4c0cbed3c898f6bff5b870e4a7f5d6f4057d62a7a4b686e" dependencies = [ "bstr", "unicode-segmentation", ] [[package]] name = "similar-asserts" version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe85670573cd6f0fa97940f26e7e6601213c3b0555246c24234131f88c5709e" dependencies = [ "console", "similar", ] [[package]] name = "sval" version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53eb957fbc79a55306d5d25d87daf3627bc3800681491cda0709eef36c748bfe" [[package]] name = "sval_buffer" version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96e860aef60e9cbf37888d4953a13445abf523c534640d1f6174d310917c410d" dependencies = [ "sval", "sval_ref", ] [[package]] name = "sval_dynamic" version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea3f2b07929a1127d204ed7cb3905049381708245727680e9139dac317ed556f" dependencies = [ "sval", ] [[package]] name = "sval_fmt" version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4e188677497de274a1367c4bda15bd2296de4070d91729aac8f0a09c1abf64d" dependencies = [ "itoa", "ryu", "sval", ] [[package]] name = "sval_json" version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32f456c07dae652744781f2245d5e3b78e6a9ebad70790ac11eb15dbdbce5282" dependencies = [ "itoa", "ryu", "sval", ] [[package]] name = "sval_nested" version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "886feb24709f0476baaebbf9ac10671a50163caa7e439d7a7beb7f6d81d0a6fb" dependencies = [ "sval", "sval_buffer", "sval_ref", ] [[package]] name = "sval_ref" version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be2e7fc517d778f44f8cb64140afa36010999565528d48985f55e64d45f369ce" dependencies = [ "sval", ] [[package]] name = "sval_serde" version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "79bf66549a997ff35cd2114a27ac4b0c2843280f2cfa84b240d169ecaa0add46" dependencies = [ "serde", "sval", "sval_nested", ] [[package]] name = "syn" version = "2.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "systemd-journal-logger" version = "2.2.0" dependencies = [ "log", "rand", "retry", "rustix", "serde", "serde_json", "similar-asserts", ] [[package]] name = "typeid" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "059d83cc991e7a42fc37bd50941885db0888e34209f8cfd9aab07ddec03bc9cf" [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-segmentation" version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" [[package]] name = "value-bag" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a84c137d37ab0142f0f2ddfe332651fdbf252e7b7dbb4e67b6c1f1b2e925101" dependencies = [ "value-bag-serde1", "value-bag-sval2", ] [[package]] name = "value-bag-serde1" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccacf50c5cb077a9abb723c5bcb5e0754c1a433f1e1de89edc328e2760b6328b" dependencies = [ "erased-serde", "serde", "serde_fmt", ] [[package]] name = "value-bag-sval2" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1785bae486022dfb9703915d42287dcb284c1ee37bd1080eeba78cc04721285b" dependencies = [ "sval", "sval_buffer", "sval_dynamic", "sval_fmt", "sval_json", "sval_ref", "sval_serde", ] [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "zerocopy" version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "byteorder", "zerocopy-derive", ] [[package]] name = "zerocopy-derive" version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", "syn", ] systemd-journal-logger-2.2.0/Cargo.toml0000644000000054660000000000100134630ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # 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. # # 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 = "2021" rust-version = "1.66" name = "systemd-journal-logger" version = "2.2.0" authors = ["Sebastian Wiesner "] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "Systemd journal logger for the log facade." documentation = "https://docs.rs/systemd-journal-logger" readme = "README.md" keywords = [ "logging", "systemd", "journal", ] categories = ["development-tools::debugging"] license = "MIT OR Apache-2.0" repository = "https://github.com/swsnr/systemd-journal-logger.rs" [package.metadata.release] allow-branch = ["main"] pre-release-commit-message = "Release {{version}}" sign-commit = true sign-tag = true tag-message = "Version {{tag_name}}" tag-prefix = "" verify = false [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = """ ## [Unreleased] ## [{{version}}] – {{date}}""" search = '## \[Unreleased\]' [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = "{{tag_name}}" search = "HEAD" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = """ [Unreleased]: https://github.com/swsnr/systemd-journal-logger.rs/compare/{{tag_name}}...HEAD [{{version}}]: """ search = '\[Unreleased\]: ' [lib] name = "systemd_journal_logger" path = "src/lib.rs" [[example]] name = "systemd_service" path = "examples/systemd_service.rs" [[test]] name = "init" path = "tests/init.rs" [[test]] name = "init_with_extra_fields" path = "tests/init_with_extra_fields.rs" [[test]] name = "journal" path = "tests/journal.rs" [[test]] name = "journal_stream" path = "tests/journal_stream.rs" harness = false [[test]] name = "log_to_journal" path = "tests/log_to_journal.rs" [[test]] name = "log_with_extra_fields" path = "tests/log_with_extra_fields.rs" [dependencies.log] version = "^0.4" features = [ "std", "kv", ] [dependencies.rustix] version = "0.38.37" features = [ "std", "fs", "net", ] default-features = false [dev-dependencies.log] version = "0.4.22" features = ["kv_std"] [dev-dependencies.rand] version = "0.8.5" [dev-dependencies.retry] version = "2.0.0" [dev-dependencies.serde] version = "1.0.210" features = ["derive"] [dev-dependencies.serde_json] version = "1.0.128" [dev-dependencies.similar-asserts] version = "1.6.0" systemd-journal-logger-2.2.0/Cargo.toml.orig000064400000000000000000000032551046102023000171360ustar 00000000000000[package] name = "systemd-journal-logger" version = "2.2.0" authors = ["Sebastian Wiesner "] license = "MIT OR Apache-2.0" readme = "README.md" repository = "https://github.com/swsnr/systemd-journal-logger.rs" documentation = "https://docs.rs/systemd-journal-logger" description = "Systemd journal logger for the log facade." categories = ["development-tools::debugging"] keywords = ["logging", "systemd", "journal"] edition = "2021" # When updating the rust-version, update the version of the compiler used # in the pipelines under .github/workflows rust-version = "1.66" [dependencies] log = { version = "^0.4", features = ["std", "kv"] } rustix = { version = "0.38.37", default-features = false, features = ["std", "fs", "net"] } [dev-dependencies] similar-asserts = "1.6.0" serde = { version = "1.0.210", features = ["derive"] } serde_json = "1.0.128" rand = "0.8.5" log = { version = "0.4.22", features = ["kv_std"] } retry = "2.0.0" [[test]] name = "journal_stream" harness = false [package.metadata.release] allow-branch = ["main"] sign-tag = true sign-commit = true pre-release-commit-message = "Release {{version}}" tag-prefix = "" tag-message = "Version {{tag_name}}" pre-release-replacements = [ { file = "CHANGELOG.md", search = "## \\[Unreleased\\]", replace = "## [Unreleased]\n\n## [{{version}}] – {{date}}", exactly = 1 }, { file = "CHANGELOG.md", search = "HEAD", replace = "{{tag_name}}", exactly = 1 }, { file = "CHANGELOG.md", search = "\\[Unreleased\\]: ", replace = "[Unreleased]: https://github.com/swsnr/systemd-journal-logger.rs/compare/{{tag_name}}...HEAD\n[{{version}}]: ", exactly = 1 }, ] # Github actions checks this for us. verify = false systemd-journal-logger-2.2.0/LICENSE-APACHE-2.0000064400000000000000000000261361046102023000164730ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. systemd-journal-logger-2.2.0/LICENSE-MIT000064400000000000000000000017771046102023000157120ustar 00000000000000Permission 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 Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. systemd-journal-logger-2.2.0/README.md000064400000000000000000000043021046102023000155200ustar 00000000000000# systemd-journal-logger A pure Rust [log] logger for the [systemd journal][1]. [log]: https://docs.rs/log [1]: https://www.freedesktop.org/software/systemd/man/systemd-journald.service.html ## Usage ```console $ cargo add systemd-journal-logger ``` Then initialize the logger at the start of `main`: ```rust use log::{info, warn, error, LevelFilter}; use systemd_journal_logger::JournalLog; JournalLog::new().unwrap().install().unwrap(); log::set_max_level(LevelFilter::Info); info!("hello log"); warn!("warning"); error!("oops"); ``` You can also add additional fields to every log message, such as the version of your executable: ```rust use log::{info, warn, error, LevelFilter}; use systemd_journal_logger::JournalLog; JournalLog::new() .unwrap() .with_extra_fields(vec![("VERSION", env!("CARGO_PKG_VERSION"))]) .with_syslog_identifier("foo".to_string()) .install().unwrap(); log::set_max_level(LevelFilter::Info); info!("this message has an extra VERSION field in the journal"); ``` These extra fields appear in the output of `journalctl --output=verbose` or in any of the JSON output formats of `journalctl`. See [systemd_service.rs](./examples/systemd_service.rs) for a simple example of logging in a systemd service which automatically falls back to a different logger if not started through systemd. ## Related projects - [rust-systemd](https://github.com/jmesmon/rust-systemd) provides a [logger implementation][1] based on the `libsystemd` C library. - [slog-journald](https://github.com/slog-rs/journald) provides an [slog] logger for the systemd journal, also based on the `libsystemd` C library. - [tracing-journald](https://github.com/tokio-rs/tracing/tree/master/tracing-journald) provides a tracing backend for the systemd journal, in a pure Rust implementation. Both loggers use mostly the same fields and priorities as this implementation. [1]: https://docs.rs/systemd/0.8.2/systemd/journal/struct.JournalLog.html [slog]: https://github.com/slog-rs/slog ## Minimum Supported Rust Version The MSRV used in this repo is best effort only and may be bumped at any time, even in patch releases. ## License Either [MIT](./LICENSE-MIT) or [Apache 2.0](./LICENSE-APACHE-2.0), at your option. systemd-journal-logger-2.2.0/deny.toml000064400000000000000000000002531046102023000160760ustar 00000000000000[graph] targets = [] [advisories] version = 2 ignore = [] [licenses] version = 2 allow = ["MIT", "Apache-2.0"] [sources] unknown-registry = "deny" unknown-git = "deny" systemd-journal-logger-2.2.0/examples/systemd_service.rs000064400000000000000000000036601046102023000216430ustar 00000000000000// Copyright Sebastian Wiesner // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(warnings, clippy::all)] //! Setup logging in a systemd service. //! //! Build this example with cargo build --example systemd_service, then run it directly: //! //! ./target/debug/examples/systemd_service //! //! This will print logs to standard error. //! //! Then run the example as a systemd user service: //! //! systemd-run --user --wait ./target/debug/examples/systemd_service //! //! Now it logs to the systemd journal; you can use journalctl --user -e --output=verbose //! to inspect it. use log::{info, LevelFilter, Log}; use std::io::prelude::*; use systemd_journal_logger::{connected_to_journal, JournalLog}; struct SimpleLogger; impl Log for SimpleLogger { fn enabled(&self, _metadata: &log::Metadata) -> bool { true } fn log(&self, record: &log::Record) { let _ = writeln!(std::io::stderr(), "{}", record.args()); } fn flush(&self) { let _ = std::io::stderr().flush(); } } fn main() { if connected_to_journal() { // If the output streams of this process are directly connected to the // systemd journal log directly to the journal to preserve structured // log entries (e.g. proper multiline messages, metadata fields, etc.) JournalLog::new() .unwrap() .with_extra_fields(vec![("VERSION", env!("CARGO_PKG_VERSION"))]) .install() .unwrap(); } else { // Otherwise fall back to logging to standard error. log::set_logger(&SimpleLogger).unwrap(); } log::set_max_level(LevelFilter::Info); info!("Hello\nworld!"); } systemd-journal-logger-2.2.0/src/client.rs000064400000000000000000000071771046102023000166710ustar 00000000000000// Copyright Sebastian Wiesner // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A journald client. use std::fs::File; use std::io::prelude::*; use std::os::fd::AsFd; use std::os::unix::net::UnixDatagram; use rustix::fs::fcntl_add_seals; use rustix::fs::memfd_create; use rustix::fs::MemfdFlags; use rustix::fs::SealFlags; use rustix::io::Errno; use rustix::net::sendmsg_unix; use rustix::net::SendAncillaryBuffer; use rustix::net::SendFlags; use rustix::net::SocketAddrUnix; const JOURNALD_PATH: &str = "/run/systemd/journal/socket"; pub struct JournalClient { socket: UnixDatagram, } impl JournalClient { pub fn new() -> std::io::Result { let client = Self { socket: UnixDatagram::unbound()?, }; // Check that we can talk to journald, by sending empty payload which journald discards. // However if the socket didn't exist or if none listened we'd get an error here. client.send_payload(&[])?; Ok(client) } /// Send `payload` to journald. /// /// Directly send it as datagram, and fall back to [`Self::send_large_payload`] /// if that fails with `EMSGSIZE`. pub fn send_payload(&self, payload: &[u8]) -> std::io::Result { self.socket .send_to(payload, JOURNALD_PATH) .or_else(|error| { if Some(Errno::MSGSIZE) == Errno::from_io_error(&error) { self.send_large_payload(payload) } else { Err(error) } }) } /// Send a large payload to journald. /// /// Write payload to a memfd, seal it, and then send the FD to the socket in /// an ancilliary message. /// /// See . fn send_large_payload(&self, payload: &[u8]) -> std::io::Result { let mut mem: File = memfd_create( "systemd-journal-logger", MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC, )? .into(); mem.write_all(payload)?; // Fully seal the memfd to signal journald that it is safe to mmap now. fcntl_add_seals( &mem, SealFlags::SEAL | SealFlags::SHRINK | SealFlags::WRITE | SealFlags::GROW, )?; let fds = &[mem.as_fd()]; let scm_rights = rustix::net::SendAncillaryMessage::ScmRights(fds); // We use a static buffer size here, because we don't need to account // for arbitrary messages; we just need enough space for a single FD. // With a static buffer we get away without any additional heap // allocations here. let mut buffer = [0; 64]; // Just a sanity check should we ever get the static buffer size wrong. assert!( scm_rights.size() <= buffer.len(), "static buffer size not sufficient for ScmRights message of size {}", scm_rights.size() ); let mut buffer = SendAncillaryBuffer::new(&mut buffer); // push returns false if the buffer is too small to add the new message; // let's guard against this. assert!(buffer.push(scm_rights), "Failed to push ScmRights message"); let size = sendmsg_unix( &self.socket, &SocketAddrUnix::new(JOURNALD_PATH)?, &[], &mut buffer, SendFlags::NOSIGNAL, )?; Ok(size) } } systemd-journal-logger-2.2.0/src/fields.rs000064400000000000000000000115021046102023000166440ustar 00000000000000// Copyright Sebastian Wiesner // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Write well-formated journal fields to buffers. use std::fmt::Arguments; use std::io::Write; use log::kv::Value; pub enum FieldName<'a> { WellFormed(&'a str), WriteEscaped(&'a str), } /// Whether `c` is a valid character in the key of a journal field. /// /// Journal field keys may only contain ASCII uppercase letters A to Z, /// numbers 0 to 9 and the underscore. fn is_valid_key_char(c: char) -> bool { matches!(c, 'A'..='Z' | '0'..='9' | '_') } /// Escape a `key` for use in a systemd journal field. /// /// See [`crate::JournalLog`] for these rules. pub fn escape_journal_key(key: &str) -> Vec { let mut escaped = key .to_ascii_uppercase() .replace(|c| !is_valid_key_char(c), "_"); if escaped.starts_with(|c: char| matches!(c, '_' | '0'..='9')) { escaped = format!("ESCAPED_{}", escaped); } let mut payload = escaped.into_bytes(); payload.truncate(64); payload } fn put_field_name(buffer: &mut Vec, name: FieldName<'_>) { match name { FieldName::WellFormed(name) => buffer.extend_from_slice(name.as_bytes()), FieldName::WriteEscaped("") => buffer.extend_from_slice(b"EMPTY"), // FIXME: We should try to find a way to do this with less allocations. FieldName::WriteEscaped(name) => buffer.extend_from_slice(&escape_journal_key(name)), } } pub trait PutAsFieldValue { fn put_field_value(self, buffer: &mut Vec); } impl PutAsFieldValue for &[u8] { fn put_field_value(self, buffer: &mut Vec) { buffer.extend_from_slice(self) } } impl PutAsFieldValue for &Arguments<'_> { fn put_field_value(self, buffer: &mut Vec) { match self.as_str() { Some(s) => buffer.extend_from_slice(s.as_bytes()), None => write!(buffer, "{}", self).unwrap(), } } } impl<'a> PutAsFieldValue for Value<'a> { fn put_field_value(self, buffer: &mut Vec) { // TODO: We can probably write the value more efficiently by visiting it? write!(buffer, "{}", self).unwrap() } } pub fn put_field_length_encoded( buffer: &mut Vec, name: FieldName<'_>, value: V, ) { put_field_name(buffer, name); buffer.push(b'\n'); // Reserve the length tag buffer.extend_from_slice(&[0; 8]); let value_start = buffer.len(); value.put_field_value(buffer); let value_end = buffer.len(); // Fill the length tag let length_bytes = ((value_end - value_start) as u64).to_le_bytes(); buffer[value_start - 8..value_start].copy_from_slice(&length_bytes); buffer.push(b'\n'); } pub fn put_field_bytes(buffer: &mut Vec, name: FieldName<'_>, value: &[u8]) { if value.contains(&b'\n') { // Write as length encoded field put_field_length_encoded(buffer, name, value); } else { put_field_name(buffer, name); buffer.push(b'='); buffer.extend_from_slice(value); buffer.push(b'\n'); } } #[cfg(test)] mod tests { use super::*; use similar_asserts::assert_eq; use FieldName::*; #[test] fn escape_journal_key() { for case in &["FOO", "FOO_123"] { assert_eq!( &String::from_utf8_lossy(&super::escape_journal_key(case)), case ); } let cases = vec![ ("foo", "FOO"), ("_foo", "ESCAPED__FOO"), ("1foo", "ESCAPED_1FOO"), ("Hallöchen", "HALL_CHEN"), ]; for (key, expected) in cases { assert_eq!( &String::from_utf8_lossy(&super::escape_journal_key(key)), expected ); } } #[test] fn put_field_length_encoded() { let mut buffer = Vec::new(); // See "Data Format" in https://systemd.io/JOURNAL_NATIVE_PROTOCOL/ for this example super::put_field_length_encoded(&mut buffer, WellFormed("FOO"), "BAR".as_bytes()); assert_eq!(&buffer, b"FOO\n\x03\0\0\0\0\0\0\0BAR\n"); } #[test] fn put_field_bytes_no_newline() { let mut buffer = Vec::new(); super::put_field_bytes(&mut buffer, WellFormed("FOO"), "BAR".as_bytes()); assert_eq!(&buffer, b"FOO=BAR\n"); } #[test] fn put_field_bytes_newline() { let mut buffer = Vec::new(); super::put_field_bytes( &mut buffer, WellFormed("FOO"), "BAR\nSPAM_WITH_EGGS".as_bytes(), ); assert_eq!(&buffer, b"FOO\n\x12\0\0\0\0\0\0\0BAR\nSPAM_WITH_EGGS\n"); } } systemd-journal-logger-2.2.0/src/lib.rs000064400000000000000000000327401046102023000161530ustar 00000000000000// Copyright Sebastian Wiesner // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A pure Rust [log] logger for the [systemd journal][1]. //! //! [log]: https://docs.rs/log //! [1]: https://www.freedesktop.org/software/systemd/man/journalctl.html //! //! # Usage //! //! Create a [`JournalLog`] with [`JournalLog::new`] and then use [`JournalLog::install`] to //! setup journal logging. Then configure the logging level and now you can use the standard macros //! from the [`log`] crate to send log messages to the systemd journal: //! //! ```rust //! use log::{info, warn, error, LevelFilter}; //! use systemd_journal_logger::JournalLog; //! //! JournalLog::new().unwrap().install().unwrap(); //! log::set_max_level(LevelFilter::Info); //! //! info!("hello log"); //! warn!("warning"); //! error!("oops"); //! ``` //! //! See [`JournalLog`] for details about the logging format. //! //! ## Journal connections //! //! In a service you can use [`connected_to_journal`] to check whether //! the standard output or error stream of the current process is directly //! connected to the systemd journal (the default for services started by //! systemd) and fall back to logging to standard error if that's not the //! case. Take a look at the [systemd_service.rs] example for details. //! //! [systemd_service.rs]: https://github.com/swsnr/systemd-journal-logger.rs/blob/main/examples/systemd_service.rs //! //! ```rust //! use log::{info, warn, error, LevelFilter}; //! use systemd_journal_logger::JournalLog; //! //! JournalLog::new() //! .unwrap() //! .with_extra_fields(vec![("VERSION", env!("CARGO_PKG_VERSION"))]) //! .with_syslog_identifier("foo".to_string()) //! .install().unwrap(); //! log::set_max_level(LevelFilter::Info); //! //! info!("this message has an extra VERSION field in the journal"); //! ``` //! //! You can display these extra fields with `journalctl --output=verbose` and extract them with any of the structured //! output formats of `journalctl`, e.g. `journalctl --output=json`. #![deny(warnings, missing_docs, clippy::all)] #![forbid(unsafe_code)] use std::io::prelude::*; use std::os::fd::AsFd; use client::JournalClient; use log::kv::{Error, Key, Value, VisitSource}; use log::{Level, Log, Metadata, Record, SetLoggerError}; mod client; mod fields; use fields::*; /// Whether the current process is directly connected to the systemd journal. /// /// Return `true` if the device and inode numbers of the [`std::io::stderr`] /// file descriptor match the value of `$JOURNAL_STREAM` (see `systemd.exec(5)`). /// Otherwise, return `false`. pub fn connected_to_journal() -> bool { rustix::fs::fstat(std::io::stderr().as_fd()) .map(|stat| format!("{}:{}", stat.st_dev, stat.st_ino)) .ok() .and_then(|stderr| { std::env::var_os("JOURNAL_STREAM").map(|s| s.to_string_lossy() == stderr.as_str()) }) .unwrap_or(false) } /// Create a syslog identifier from the current executable. /// /// Return `None` if we're unable to determine the name, e.g. because /// [`std::env::current_exe`] failed or returned some weird name. pub fn current_exe_identifier() -> Option { let executable = std::env::current_exe().ok()?; Some(executable.file_name()?.to_string_lossy().into_owned()) } struct WriteKeyValues<'a>(&'a mut Vec); impl<'a, 'kvs> VisitSource<'kvs> for WriteKeyValues<'a> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { put_field_length_encoded(self.0, FieldName::WriteEscaped(key.as_str()), value); Ok(()) } } /// A systemd journal logger. /// /// ## Journal access /// /// ## Standard fields /// /// The journald logger always sets the following standard [journal fields]: /// /// - `PRIORITY`: The log level mapped to a priority (see below). /// - `MESSAGE`: The formatted log message (see [`log::Record::args()`]). /// - `SYSLOG_PID`: The PID of the running process (see [`std::process::id()`]). /// - `CODE_FILE`: The filename the log message originates from (see [`log::Record::file()`], only if present). /// - `CODE_LINE`: The line number the log message originates from (see [`log::Record::line()`], only if present). /// /// It also sets `SYSLOG_IDENTIFIER` if non-empty (see [`JournalLog::with_syslog_identifier`]). /// /// Additionally it also adds the following non-standard fields: /// /// - `TARGET`: The target of the log record (see [`log::Record::target()`]). /// - `CODE_MODULE`: The module path of the log record (see [`log::Record::module_path()`], only if present). /// /// [journal fields]: https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html /// /// ## Log levels and Priorities /// /// [`log::Level`] gets mapped to journal (syslog) priorities as follows: /// /// - [`Level::Error`] → `3` (err) /// - [`Level::Warn`] → `4` (warning) /// - [`Level::Info`] → `5` (notice) /// - [`Level::Debug`] → `6` (info) /// - [`Level::Trace`] → `7` (debug) /// /// Higher priorities (crit, alert, and emerg) are not used. /// /// ## Custom fields and structured record fields /// /// In addition to these fields the logger also adds all structures key-values /// (see [`log::Record::key_values`]) from each log record as journal fields, /// and also supports global extra fields via [`Self::with_extra_fields`]. /// /// Journald allows only ASCII uppercase letters, ASCII digits, and the /// underscore in field names, and limits field names to 64 bytes. See upstream's /// [`journal_field_valid`][jfv] for the precise validation rules. /// /// This logger mangles the keys of additional key-values on records and names /// of custom fields according to the following rules, to turn them into valid /// journal fields: /// /// - If the key is entirely empty, use `EMPTY`. /// - Transform the entire value to ASCII uppercase. /// - Replace all invalid characters with underscore. /// - If the key starts with an underscore or digit, which is not permitted, /// prepend `ESCAPED_`. /// - Cap the result to 64 bytes. /// /// [jfv]: https://github.com/systemd/systemd/blob/a8b53f4f1558b17169809effd865232580e4c4af/src/libsystemd/sd-journal/journal-file.c#L1698 /// /// # Errors /// /// The logger tries to connect to journald when constructed, to provide early /// on feedback if journald is not available (e.g. in containers where the /// journald socket is not mounted into the container). /// /// Later on, the logger simply ignores any errors when sending log records to /// journald, simply because the log interface does not expose faillible operations. pub struct JournalLog { /// The journald client client: JournalClient, /// Preformatted extra fields to be appended to every log message. extra_fields: Vec, /// The syslog identifier. syslog_identifier: String, } fn record_payload(syslog_identifier: &str, record: &Record) -> Vec { use FieldName::*; let mut buffer = Vec::with_capacity(1024); // Write standard fields. Numeric fields can't contain new lines so we // write them directly, everything else goes through the put functions // for property mangling and length-encoding let priority = match record.level() { Level::Error => b"3", Level::Warn => b"4", Level::Info => b"5", Level::Debug => b"6", Level::Trace => b"7", }; put_field_bytes(&mut buffer, WellFormed("PRIORITY"), priority); put_field_length_encoded(&mut buffer, WellFormed("MESSAGE"), record.args()); // Syslog compatibility fields writeln!(&mut buffer, "SYSLOG_PID={}", std::process::id()).unwrap(); if !syslog_identifier.is_empty() { put_field_bytes( &mut buffer, WellFormed("SYSLOG_IDENTIFIER"), syslog_identifier.as_bytes(), ); } if let Some(file) = record.file() { put_field_bytes(&mut buffer, WellFormed("CODE_FILE"), file.as_bytes()); } if let Some(module) = record.module_path() { put_field_bytes(&mut buffer, WellFormed("CODE_MODULE"), module.as_bytes()); } if let Some(line) = record.line() { writeln!(&mut buffer, "CODE_LINE={}", line).unwrap(); } put_field_bytes( &mut buffer, WellFormed("TARGET"), record.target().as_bytes(), ); // Put all structured values of the record record .key_values() .visit(&mut WriteKeyValues(&mut buffer)) .unwrap(); buffer } impl JournalLog { /// Create a journal log instance with a default syslog identifier. pub fn new() -> std::io::Result { let logger = Self::empty()?; Ok(logger.with_syslog_identifier(current_exe_identifier().unwrap_or_default())) } /// Create an empty journal log instance, with no extra fields and no syslog /// identifier. /// /// See [`Self::with_syslog_identifier`] and [`Self::with_extra_fields`] to /// set either. It's recommended to at least set the syslog identifier. pub fn empty() -> std::io::Result { Ok(Self { client: JournalClient::new()?, extra_fields: Vec::new(), syslog_identifier: String::new(), }) } /// Install this logger globally. /// /// See [`log::set_boxed_logger`]. pub fn install(self) -> Result<(), SetLoggerError> { log::set_boxed_logger(Box::new(self)) } /// Add an extra field to be added to every log entry. /// /// `name` is the name of a custom field, and `value` its value. Fields are /// appended to every log entry, in order they were added to the logger. /// /// ## Restrictions on field names /// /// `name` should be a valid journal file name, i.e. it must only contain /// ASCII uppercase alphanumeric characters and the underscore, and must /// start with an ASCII uppercase letter. /// /// Invalid keys in `extra_fields` are escaped according to the rules /// documented in [`JournalLog`]. /// /// It is not recommended that `name` is any of the standard fields already /// added by this logger (see [`JournalLog`]); though journald supports /// multiple values for a field, journald clients may not handle unexpected /// multi-value fields properly and perhaps only show the first value. /// Specifically, even `journalctl` will only shouw the first `MESSAGE` value /// of journal entries. /// /// ## Restrictions on values /// /// There are no restrictions on the value. pub fn add_extra_field, V: AsRef<[u8]>>(mut self, name: K, value: V) -> Self { put_field_bytes( &mut self.extra_fields, FieldName::WriteEscaped(name.as_ref()), value.as_ref(), ); self } /// Set extra fields to be added to every log entry. /// /// Remove all previously added fields. /// /// See [`Self::add_extra_field`] for details. pub fn with_extra_fields(mut self, extra_fields: I) -> Self where I: IntoIterator, K: AsRef, V: AsRef<[u8]>, { self.extra_fields.clear(); let mut logger = self; for (name, value) in extra_fields { logger = logger.add_extra_field(name, value); } logger } /// Set the given syslog identifier for this logger. /// /// The logger writes this string in the `SYSLOG_IDENTIFIER` field, which /// can be filtered for with `journalctl -t`. /// /// Use [`current_exe_identifier()`] to obtain the standard identifier for /// the current executable. pub fn with_syslog_identifier(mut self, identifier: String) -> Self { self.syslog_identifier = identifier; self } /// Get the complete journal payload for `record`, including extra fields /// from this logger. fn record_payload(&self, record: &Record) -> Vec { let mut payload = record_payload(&self.syslog_identifier, record); payload.extend_from_slice(&self.extra_fields); payload } /// Send a single log record to the journal. /// /// Extract all fields (standard and custom) from `record` (`see [`JournalLog`]), /// append all `extra_fields` given to this logger, and send the result to /// journald. pub fn journal_send(&self, record: &Record) -> std::io::Result<()> { let _ = self.client.send_payload(&self.record_payload(record))?; Ok(()) } } /// The [`Log`] interface for [`JournalLog`]. impl Log for JournalLog { /// Whether this logger is enabled. /// /// Always returns `true`. fn enabled(&self, _metadata: &Metadata) -> bool { true } /// Send the given `record` to the systemd journal. /// /// # Errors /// /// Ignore any errors which occur when sending `record` to journald because /// we cannot reasonably handle them at this place. /// /// See [`JournalLog::journal_send`] for a function which returns any error /// which might have occurred while sending the `record` to the journal. fn log(&self, record: &Record) { // We can't really handle errors here, so simply discard them. // The alternative would be to panic, but a failed logging call should // not bring the entire process down. let _ = self.journal_send(record); } /// Flush log records. /// /// A no-op for journal logging. fn flush(&self) {} } systemd-journal-logger-2.2.0/tests/init.rs000064400000000000000000000014341046102023000167170ustar 00000000000000// Copyright Sebastian Wiesner // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(warnings, clippy::all)] use log::info; mod journal; use similar_asserts::assert_eq; use systemd_journal_logger::JournalLog; #[test] fn init() { JournalLog::new().unwrap().install().unwrap(); log::set_max_level(log::LevelFilter::Info); info!(target: "init", "Hello World"); let entry = journal::read_one_entry("init"); assert_eq!(entry["TARGET"], "init"); assert_eq!(entry["MESSAGE"], "Hello World"); } systemd-journal-logger-2.2.0/tests/init_with_extra_fields.rs000064400000000000000000000017431046102023000225060ustar 00000000000000// Copyright Sebastian Wiesner // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(warnings, clippy::all)] use log::info; mod journal; use similar_asserts::assert_eq; use systemd_journal_logger::JournalLog; #[test] fn init_with_extra_fields() { JournalLog::new() .unwrap() .with_extra_fields(vec![("SPAM", "WITH EGGS")]) .install() .unwrap(); log::set_max_level(log::LevelFilter::Info); info!(target: "init_with_extra_fields", "Hello World"); let entry = journal::read_one_entry("init_with_extra_fields"); assert_eq!(entry["TARGET"], "init_with_extra_fields"); assert_eq!(entry["MESSAGE"], "Hello World"); assert_eq!(entry["SPAM"], "WITH EGGS"); } systemd-journal-logger-2.2.0/tests/journal.rs000064400000000000000000000100371046102023000174250ustar 00000000000000// Copyright Sebastian Wiesner // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Journal access for integration tests. #![allow(dead_code)] use std::borrow::Cow; use std::collections::HashMap; use std::fmt::Display; use std::process::Command; use retry::delay::Fixed; use serde::Deserialize; use std::ffi::OsStr; #[derive(Debug, Copy, Clone)] pub enum Journal { User, System, } #[derive(Debug, PartialEq, Deserialize)] #[serde(untagged)] pub enum FieldValue { Text(String), Array(Vec), Binary(Vec), } impl FieldValue { pub fn as_text(&self) -> Cow<'_, str> { match self { FieldValue::Text(v) => Cow::Borrowed(v.as_str()), FieldValue::Binary(binary) => String::from_utf8_lossy(binary), FieldValue::Array(v) => Cow::Borrowed(v.first().map_or("", |s| s.as_str())), } } } impl Display for FieldValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.as_text().fmt(f) } } // Convenience impls to compare fields against strings and bytes with assert_eq! impl PartialEq<&str> for FieldValue { fn eq(&self, other: &&str) -> bool { match self { FieldValue::Text(s) => s == other, FieldValue::Binary(b) => b == other.as_bytes(), FieldValue::Array(_) => false, } } } // Convenience impls to compare fields against strings and bytes with assert_eq! impl PartialEq for FieldValue { fn eq(&self, other: &String) -> bool { self == &other.as_str() } } // Convenience impls to compare fields against strings and bytes with assert_eq! impl PartialEq<&String> for FieldValue { fn eq(&self, other: &&String) -> bool { self == &other.as_str() } } impl PartialEq<[u8]> for FieldValue { fn eq(&self, other: &[u8]) -> bool { match self { FieldValue::Text(s) => s.as_bytes() == other, FieldValue::Binary(data) => data == other, FieldValue::Array(_) => false, } } } impl PartialEq> for FieldValue { fn eq(&self, other: &std::vec::Vec<&str>) -> bool { match self { FieldValue::Text(_) => false, FieldValue::Binary(_) => false, FieldValue::Array(a) => a == other, } } } /// Read from journal. /// /// `args` contains additional journalctl arguments such as filters. pub fn read(journal: Journal, args: I) -> Vec> where I: IntoIterator, S: AsRef, { let mut command = Command::new("journalctl"); if matches!(journal, Journal::User) { command.arg("--user"); } let stdout = String::from_utf8( command .arg("--output=json") // We pass --all to circumvent journalctl's default limit of 4096 bytes for field values .arg("--all") .args(args) .output() .unwrap() .stdout, ) .unwrap(); stdout .lines() .map(|l| serde_json::from_str(l).unwrap()) .collect() } // Read from the journal of the current process. pub fn read_current_process(target: &str) -> Vec> { // Filter by the PID of the current test process and the module path read( Journal::User, vec![ format!("_PID={}", std::process::id()), format!("TARGET={}", target), ], ) } pub fn read_one_entry(target: &str) -> HashMap { retry::retry(Fixed::from_millis(100).take(30), || { let mut entries = read_current_process(target); if entries.len() == 1 { Ok(entries.pop().unwrap()) } else { Err(format!("No entries in journal for target {}", target)) } }) .unwrap() } systemd-journal-logger-2.2.0/tests/journal_stream.rs000064400000000000000000000066161046102023000210100ustar 00000000000000// Copyright Sebastian Wiesner // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Test whether connected_to_journal successfully detects a journal //! connection under a systemd environment. //! //! We do this with a small custom executable without the standard //! test harness which restarts itself in a transient user service //! with systemd-run, and then calls connected_to_journal and logs //! the return value to the systemd journal. //! //! The main process waits until the transient service finished //! and then looks for the journal entry and asserts its contents. #![deny(warnings, clippy::all)] use std::env::VarError; use std::process::Command; use log::{info, LevelFilter}; use similar_asserts::assert_eq; mod journal; fn main() { let env_name = "_TEST_LOG_TARGET"; // On Github Actions use the system instance for this test, because there's // no user instance running apparently. let use_system_instance = std::env::var_os("GITHUB_ACTIONS").is_some(); match std::env::var(env_name) { Ok(target) => { use systemd_journal_logger::*; JournalLog::new().unwrap().install().unwrap(); log::set_max_level(LevelFilter::Debug); info!( target: &target, "connected_to_journal() -> {}", connected_to_journal() ); } Err(VarError::NotUnicode(value)) => { panic!("Value of ${} not unicode: {:?}", env_name, value); } Err(VarError::NotPresent) => { // Attach our PID to the target to make the target unique. let target = format!("journal_stream_{}", std::process::id()); // Restart this binary under systemd-run and then check the journal for the test result let exe = std::env::current_exe().unwrap(); let status = if use_system_instance { let mut cmd = Command::new("sudo"); cmd.arg("systemd-run"); cmd } else { let mut cmd = Command::new("systemd-run"); cmd.arg("--user"); cmd } .arg("--description=systemd-journal-logger integration test: journal_stream") .arg(format!("--setenv={}={}", env_name, &target)) // Wait until the process exited and unload the entire unit afterwards to // leave no state behind .arg("--wait") .arg("--collect") .arg(exe) .status() .unwrap(); assert!(status.success()); let journal = if use_system_instance { journal::Journal::System } else { journal::Journal::User }; let entries = journal::read( journal, vec![ format!("CODE_MODULE={}", module_path!()), format!("TARGET={}", &target), ], ); assert_eq!(entries.len(), 1); assert_eq!(entries[0]["TARGET"], &target); assert_eq!(entries[0]["MESSAGE"], "connected_to_journal() -> true"); } } } systemd-journal-logger-2.2.0/tests/log_to_journal.rs000064400000000000000000000152311046102023000207710ustar 00000000000000// Copyright Sebastian Wiesner // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Test that we actually log to the systemd journal, //! and that systemd can pick all those messages up.log_ #![deny(warnings, clippy::all)] use log::kv::Value; use log::{Level, Log, Record}; use similar_asserts::assert_eq; use systemd_journal_logger::JournalLog; mod journal; #[test] fn simple_log_entry() { JournalLog::new().unwrap().log( &Record::builder() .level(Level::Warn) .target("simple_log_entry") .module_path(Some(module_path!())) .file(Some(file!())) .line(Some(92749)) .args(format_args!("systemd_journal_logger test: {}", 42)) .build(), ); let entry = journal::read_one_entry("simple_log_entry"); assert_eq!(entry["TARGET"], "simple_log_entry"); assert_eq!(entry["PRIORITY"], "4"); assert_eq!(entry["MESSAGE"], "systemd_journal_logger test: 42"); assert_eq!(entry["CODE_FILE"], file!()); assert_eq!(entry["CODE_LINE"], "92749"); assert_eq!(entry["CODE_MODULE"], module_path!()); assert!(entry["SYSLOG_IDENTIFIER"] .as_text() .contains("log_to_journal")); assert_eq!( entry["SYSLOG_IDENTIFIER"], std::env::current_exe() .unwrap() .file_name() .unwrap() .to_str() .unwrap() ); assert_eq!(entry["SYSLOG_PID"], std::process::id().to_string()); // // The PID we logged is equal to the PID systemd determined as source for our process assert_eq!(entry["SYSLOG_PID"], entry["_PID"]); } #[test] fn internal_null_byte_in_message() { JournalLog::new().unwrap().log( &Record::builder() .level(Level::Warn) .target("internal_null_byte_in_message") .args(format_args!("systemd_journal_logger with \x00 byte")) .build(), ); let entry = journal::read_one_entry("internal_null_byte_in_message"); assert_eq!(entry["PRIORITY"], "4"); assert_eq!( entry["MESSAGE"].as_text(), "systemd_journal_logger with \x00 byte" ); } #[test] fn multiline_message() { JournalLog::new().unwrap().log( &Record::builder() .level(Level::Error) .target("multiline_message") .args(format_args!( "systemd_journal_logger test\nwith\nline {}", "breaks" )) .build(), ); let entry = journal::read_one_entry("multiline_message"); assert_eq!(entry["PRIORITY"], "3"); assert_eq!( entry["MESSAGE"], "systemd_journal_logger test\nwith\nline breaks" ); } #[test] fn trailing_newline_message() { JournalLog::new().unwrap().log( &Record::builder() .level(Level::Trace) .target("trailing_newline_message") .args(format_args!("trailing newline\n")) .build(), ); let entry = journal::read_one_entry("trailing_newline_message"); assert_eq!(entry["PRIORITY"], "7"); assert_eq!(entry["MESSAGE"], "trailing newline\n"); } #[test] fn very_large_message() { let very_large_string = "b".repeat(512_000); JournalLog::new().unwrap().log( &Record::builder() .level(Level::Trace) .target("very_large_message") .args(format_args!("{}", very_large_string)) .build(), ); let entry = journal::read_one_entry("very_large_message"); assert_eq!(entry["PRIORITY"], "7"); assert_eq!(entry["MESSAGE"].as_text(), very_large_string); } #[test] fn extra_fields() { JournalLog::new() .unwrap() .with_extra_fields(vec![("FOO", "BAR")]) .log( &Record::builder() .level(Level::Debug) .target("extra_fields") .args(format_args!("with an extra field")) .build(), ); let entry = journal::read_one_entry("extra_fields"); assert_eq!(entry["PRIORITY"], "6"); assert_eq!(entry["MESSAGE"], "with an extra field"); assert_eq!(entry["FOO"], "BAR") } #[test] fn escaped_extra_fields() { JournalLog::new() .unwrap() .with_extra_fields(vec![ ("Hallöchen", "Welt"), ("123_FOO", "BAR"), ("_spam", "EGGS"), ]) .log( &Record::builder() .level(Level::Debug) .target("escaped_extra_fields") .args(format_args!("with an escaped extra field")) .build(), ); let entry = journal::read_one_entry("escaped_extra_fields"); assert_eq!(entry["PRIORITY"], "6"); assert_eq!(entry["MESSAGE"], "with an escaped extra field"); assert_eq!(entry["HALL_CHEN"], "Welt"); assert_eq!(entry["ESCAPED_123_FOO"], "BAR"); assert_eq!(entry["ESCAPED__SPAM"], "EGGS"); } #[test] fn extra_record_fields() { let kvs: &[(&str, Value)] = &[ ("_foo", Value::from("foo")), ("spam_with_eggs", Value::from(false)), ]; JournalLog::new() .unwrap() .with_extra_fields(vec![("EXTRA_FIELD", "foo")]) .log( &Record::builder() .level(Level::Error) .target("extra_record_fields") .args(format_args!("Hello world")) .key_values(&kvs) .build(), ); let entry = journal::read_one_entry("extra_record_fields"); assert_eq!(entry["PRIORITY"], "3"); assert_eq!(entry["MESSAGE"], "Hello world"); assert_eq!(entry["EXTRA_FIELD"], "foo"); assert_eq!(entry["ESCAPED__FOO"], "foo"); assert_eq!(entry["SPAM_WITH_EGGS"], "false"); } #[test] fn duplicate_fields() { let kvs: &[(&str, Value)] = &[("FOO", Value::from("record foo"))]; JournalLog::new() .unwrap() .with_extra_fields(vec![("FOO", "logger foo")]) .log( &Record::builder() .level(Level::Error) .target("duplicate_fields") .args(format_args!("Hello world")) .key_values(&kvs) .build(), ); let entry = journal::read_one_entry("duplicate_fields"); assert_eq!(entry["PRIORITY"], "3"); assert_eq!(entry["MESSAGE"], "Hello world"); // First the field value from the record, then the one from the logger itself, // since we append extra fields of the logger at the very end. assert_eq!(entry["FOO"], vec!["record foo", "logger foo"]); } systemd-journal-logger-2.2.0/tests/log_with_extra_fields.rs000064400000000000000000000023271046102023000223230ustar 00000000000000// Copyright Sebastian Wiesner // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(warnings, clippy::all)] mod journal; use similar_asserts::assert_eq; use systemd_journal_logger::JournalLog; #[derive(Debug)] struct SomeDummy { #[allow(dead_code)] foo: usize, } #[test] fn log_with_extra_fields() { JournalLog::new().unwrap().install().unwrap(); log::set_max_level(log::LevelFilter::Info); let error = std::io::Error::new( std::io::ErrorKind::NotFound, "not found: the important file", ); let dummy = SomeDummy { foo: 42 }; log::error!(target: "log_with_extra_fields", dummy:?, spam = "no eggs", error:err; "Hello World"); let entry = journal::read_one_entry("log_with_extra_fields"); assert_eq!(entry["MESSAGE"], "Hello World"); assert_eq!(entry["SPAM"], "no eggs"); assert_eq!(entry["ERROR"], "not found: the important file"); assert_eq!(entry["DUMMY"], format!("{:?}", dummy)); }