systemd-journal-logger-2.2.2/.cargo_vcs_info.json0000644000000001360000000000100154540ustar { "git": { "sha1": "41351fb0e5e3f489f37f55680f026d266f9cb6c6" }, "path_in_vcs": "" }systemd-journal-logger-2.2.2/.github/dependabot.yml000064400000000000000000000004751046102023000204420ustar 00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: monthly assignees: [swsnr] - package-ecosystem: "cargo" directory: "/" schedule: interval: monthly assignees: [swsnr] ignore: - update-types: ["version-update:semver-patch"] systemd-journal-logger-2.2.2/.gitignore000064400000000000000000000000101046102023000162230ustar 00000000000000/target systemd-journal-logger-2.2.2/CHANGELOG.md000064400000000000000000000152171046102023000160630ustar 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.2] – 2025-05-03 ### Changed - Move to . - Bump MSRV to 1.68. ## [2.2.1] – 2025-03-25 ### Changed - Update to rustix 1. ## [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://codeberg.org/swsnr/systemd-journal-logger.rs/pulls/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://codeberg.org/swsnr/systemd-journal-logger.rs/pulls/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://codeberg.org/swsnr/systemd-journal-logger.rs/issues/16 [GH-17]: https://codeberg.org/swsnr/systemd-journal-logger.rs/pulls/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://codeberg.org/swsnr/systemd-journal-logger.rs/pulls/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://codeberg.org/swsnr/systemd-journal-logger.rs/pulls/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://codeberg.org/swsnr/systemd-journal-logger.rs/pulls/1 [GH-3]: https://codeberg.org/swsnr/systemd-journal-logger.rs/pulls/3 [GH-5]: https://codeberg.org/swsnr/systemd-journal-logger.rs/pulls/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://codeberg.org/swsnr/systemd-journal-logger.rs/pulls/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/pulls/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://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v2.2.2...HEAD [2.2.2]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v2.2.1...v2.2.2 [2.2.1]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v2.2.0...v2.2.1 [2.2.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v2.1.1...v2.2.0 [2.1.1]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v2.1.0...v2.1.1 [2.1.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v2.0.0...v2.1.0 [2.0.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v1.0.0...v2.0.0 [1.0.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v0.7.0...v1.0.0 [0.7.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v0.6.0...v0.7.0 [0.6.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v0.5.1...v0.6.0 [0.5.1]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v0.5.0...v0.5.1 [0.5.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v0.4.1...v0.5.0 [0.4.1]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v0.4.0...v0.4.1 [0.4.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v0.3.1...v0.4.0 [0.3.1]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v0.3.0...v0.3.1 [0.3.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v0.2.0...v0.3.0 [0.2.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/compare/v0.1.0...v0.2.0 [0.1.0]: https://codeberg.org/swsnr/systemd-journal-logger.rs/releases/tag/v0.1.0 systemd-journal-logger-2.2.2/Cargo.lock0000644000000325620000000000100134370ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bitflags" version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" [[package]] name = "bstr" version = "1.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "531a9155a481e2ee699d4f98f43c0ca4ff8ee1bfd55c31e9e98fb29d2b176fe0" 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.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea3c6ecd8059b57859df5c69830340ed3c41d30e3da0c1cbed90a96ac853041b" dependencies = [ "encode_unicode", "libc", "once_cell", "windows-sys", ] [[package]] name = "encode_unicode" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" [[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.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" 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.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "libc" version = "0.2.171" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" [[package]] name = "linux-raw-sys" version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe7db12097d22ec582439daf8618b8fdd1a7bef6270e9af3b1ebcd30893cf413" [[package]] name = "log" version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e" dependencies = [ "value-bag", ] [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "once_cell" version = "1.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" [[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.94" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" 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.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" [[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 = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e56a18552996ac8d29ecc3b190b4fdbb2d91ca4ec396de7bbffaf43f3d637e96" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "serde" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" 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.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" dependencies = [ "itoa", "memchr", "ryu", "serde", ] [[package]] name = "similar" version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" dependencies = [ "bstr", "unicode-segmentation", ] [[package]] name = "similar-asserts" version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5b441962c817e33508847a22bd82f03a30cff43642dc2fae8b050566121eb9a" dependencies = [ "console", "similar", ] [[package]] name = "sval" version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4c2f18f53c889ec3dfe1c08b20fd51406d09b14bf18b366416718763ccff05a" [[package]] name = "sval_buffer" version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b8cb1bb48d0bed828b908e6b99e7ab8c7244994dc27948a2e31d42e8c4d77c1" dependencies = [ "sval", "sval_ref", ] [[package]] name = "sval_dynamic" version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba574872d4ad653071a9db76c49656082db83a37cd5f559874273d36b4a02b9d" dependencies = [ "sval", ] [[package]] name = "sval_fmt" version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "944450b2dbbf8aae98537776b399b23d72b19243ee42522cfd110305f3c9ba5a" dependencies = [ "itoa", "ryu", "sval", ] [[package]] name = "sval_json" version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "411bbd543c413796ccfbaa44f6676e20032b6c69e4996cb6c3e6ef30c79b96d1" dependencies = [ "itoa", "ryu", "sval", ] [[package]] name = "sval_nested" version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f30582d2a90869b380f8260559138c1b68ac3e0765520959f22a1a1fdca31769" dependencies = [ "sval", "sval_buffer", "sval_ref", ] [[package]] name = "sval_ref" version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "762d3fbf3c0869064b7c93808c67ad2ed0292dde9b060ac282817941d4707dff" dependencies = [ "sval", ] [[package]] name = "sval_serde" version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "752d307438c6a6a3d095a2fecf6950cfb946d301a5bd6b57f047db4f6f8d97b9" dependencies = [ "serde", "sval", "sval_nested", ] [[package]] name = "syn" version = "2.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "systemd-journal-logger" version = "2.2.2" dependencies = [ "log", "retry", "rustix", "serde", "serde_json", "similar-asserts", ] [[package]] name = "typeid" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "unicode-segmentation" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" [[package]] name = "value-bag" version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ef4c4aa54d5d05a279399bfa921ec387b7aba77caf7a682ae8d86785b8fdad2" dependencies = [ "value-bag-serde1", "value-bag-sval2", ] [[package]] name = "value-bag-serde1" version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4bb773bd36fd59c7ca6e336c94454d9c66386416734817927ac93d81cb3c5b0b" dependencies = [ "erased-serde", "serde", "serde_fmt", ] [[package]] name = "value-bag-sval2" version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53a916a702cac43a88694c97657d449775667bcd14b70419441d05b7fea4a83a" 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.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" 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.2/Cargo.toml0000644000000056330000000000100134610ustar # 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.68" name = "systemd-journal-logger" version = "2.2.2" authors = ["Sebastian Wiesner "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Systemd journal logger for the log facade." homepage = "https://codeberg.org/swsnr/systemd-journal-logger.rs" 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://codeberg.org/swsnr/systemd-journal-logger.rs.git" [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 = "" [[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://codeberg.org/swsnr/systemd-journal-logger.rs/compare/{{tag_name}}...HEAD [{{version}}]: """ search = '\[Unreleased\]: ' [lib] name = "systemd_journal_logger" path = "src/lib.rs" [[example]] name = "custom_fields" path = "examples/custom_fields.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 = "1.0.3" features = [ "std", "fs", "net", ] default-features = false [dev-dependencies.log] version = "0.4.25" features = ["kv_std"] [dev-dependencies.retry] version = "2.0.0" [dev-dependencies.serde] version = "1.0.217" features = ["derive"] [dev-dependencies.serde_json] version = "1.0.138" [dev-dependencies.similar-asserts] version = "1.6.1" systemd-journal-logger-2.2.2/Cargo.toml.orig000064400000000000000000000032321046102023000171330ustar 00000000000000[package] name = "systemd-journal-logger" version = "2.2.2" authors = ["Sebastian Wiesner "] license = "MIT OR Apache-2.0" readme = "README.md" homepage = "https://codeberg.org/swsnr/systemd-journal-logger.rs" repository = "https://codeberg.org/swsnr/systemd-journal-logger.rs.git" 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 toolchain version in justfile too rust-version = "1.68" [dependencies] log = { version = "^0.4", features = ["std", "kv"] } rustix = { version = "1.0.3", default-features = false, features = [ "std", "fs", "net", ] } [dev-dependencies] similar-asserts = "1.6.1" serde = { version = "1.0.217", features = ["derive"] } serde_json = "1.0.138" log = { version = "0.4.25", 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://codeberg.org/swsnr/systemd-journal-logger.rs/compare/{{tag_name}}...HEAD\n[{{version}}]: ", exactly = 1 }, ] systemd-journal-logger-2.2.2/LICENSE-APACHE-2.0000064400000000000000000000261361046102023000164750ustar 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.2/LICENSE-MIT000064400000000000000000000017771046102023000157140ustar 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.2/README.md000064400000000000000000000043021046102023000155220ustar 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.2/deny.toml000064400000000000000000000003051046102023000160760ustar 00000000000000[graph] targets = ['x86_64-unknown-linux-gnu'] [advisories] version = 2 ignore = [] [licenses] version = 2 allow = ["MIT", "Apache-2.0"] [sources] unknown-registry = "deny" unknown-git = "deny" systemd-journal-logger-2.2.2/examples/custom_fields.rs000064400000000000000000000033521046102023000212730ustar 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)] //! Add custom fields to every emitted log record. //! //! This example demonstrates how to add arbitrary extra fields to log records //! emitted to the journald. //! //! This approach extends the key/value pairs attached to a log record with new //! pairs, in a generic way, which works with any underlying logger //! implementation. use log::kv::ToValue; use log::Log; use systemd_journal_logger::JournalLog; /// A logger which adds the thread ID to every log record. struct AddThreadId(L); impl Log for AddThreadId { fn enabled(&self, metadata: &log::Metadata) -> bool { self.0.enabled(metadata) } fn log(&self, record: &log::Record) { let thread_id = format!("{:?}", std::thread::current().id()); let extra_fields = &[("THREAD_ID", thread_id.to_value())]; self.0.log( &record .to_builder() .key_values(&[record.key_values(), &extra_fields]) .build(), ); } fn flush(&self) { self.0.flush(); } } fn main() { let log = AddThreadId( JournalLog::new() .unwrap() .with_extra_fields(vec![("VERSION", env!("CARGO_PKG_VERSION"))]), ); log::set_boxed_logger(Box::new(log)).unwrap(); log::set_max_level(log::LevelFilter::Trace); log::info!(hello = "world"; "A info message"); } systemd-journal-logger-2.2.2/examples/systemd_service.rs000064400000000000000000000036601046102023000216450ustar 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.2/justfile000064400000000000000000000012541046102023000160160ustar 00000000000000default: just --list vet: # Only consider Linux dependencies, as that's all I care for. # Seems to be unofficial, see https://github.com/mozilla/cargo-vet/issues/579, but works env CARGO_BUILD_TARGET=x86_64-unknown-linux-gnu cargo vet --locked test-all: vet cargo +stable deny --all-features --locked check cargo +stable fmt -- --check cargo +stable clippy --all-targets --locked # Stable build, test, and docs cargo +stable build --locked cargo +stable test --locked cargo +stable doc # MSRV cargo +1.68 build --locked --all-targets # semver checks cargo semver-checks release *ARGS: test-all cargo release {{ARGS}} systemd-journal-logger-2.2.2/src/client.rs000064400000000000000000000065411046102023000166650ustar 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::mem::MaybeUninit; 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_addr; use rustix::net::SendAncillaryBuffer; use rustix::net::SendAncillaryMessage; 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, )?; // Allocate a control buffer for the one file descriptor we will send let mut buffer = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))]; let mut buffer = SendAncillaryBuffer::new(&mut buffer); // Write the file descriptor to the control buffer let fds = &[mem.as_fd()]; // push returns false if the buffer is too small to add the new message; // let's guard against this. assert!( buffer.push(SendAncillaryMessage::ScmRights(fds)), "Failed to push ScmRights message" ); let size = sendmsg_addr( &self.socket, &SocketAddrUnix::new(JOURNALD_PATH)?, &[], &mut buffer, SendFlags::NOSIGNAL, )?; Ok(size) } } systemd-journal-logger-2.2.2/src/fields.rs000064400000000000000000000114761046102023000166600ustar 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 PutAsFieldValue for Value<'_> { 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.2/src/lib.rs000064400000000000000000000327441046102023000161610ustar 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://codeberg.org/swsnr/systemd-journal-logger.rs/src/branch/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<'kvs> VisitSource<'kvs> for WriteKeyValues<'_> { 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.2/supply-chain/audits.toml000064400000000000000000000036751046102023000210610ustar 00000000000000 # cargo-vet audits file [[audits.errno]] who = "Sebastian Wiesner " criteria = "safe-to-deploy" delta = "0.3.3 -> 0.3.9" notes = "Changes to unsafe code seem sound; mutable buffer is passed with appropriate buffer length." [[audits.log]] who = "Sebastian Wiesner " criteria = "safe-to-deploy" delta = "0.4.25 -> 0.4.26" notes = "Trivial code changes only" [[audits.retry]] who = "Sebastian Wiesner " criteria = "safe-to-run" version = "2.0.0" [[audits.serde]] who = "Sebastian Wiesner " criteria = "safe-to-deploy" delta = "1.0.217 -> 1.0.218" notes = "No actual code changes" [[audits.serde_derive]] who = "Sebastian Wiesner " criteria = "safe-to-deploy" delta = "1.0.217 -> 1.0.218" notes = "No code changes" [[audits.similar-asserts]] who = "Sebastian Wiesner " criteria = "safe-to-run" delta = "1.6.1 -> 1.7.0" [[trusted.erased-serde]] criteria = "safe-to-deploy" user-id = 3618 # David Tolnay (dtolnay) start = "2020-01-06" end = "2026-03-01" [[trusted.libc]] criteria = "safe-to-deploy" user-id = 51017 # Yuki Okushi (JohnTitor) start = "2020-03-17" end = "2026-03-01" [[trusted.linux-raw-sys]] criteria = "safe-to-deploy" user-id = 6825 # Dan Gohman (sunfishcode) start = "2021-06-12" end = "2026-03-01" [[trusted.memchr]] criteria = "safe-to-deploy" user-id = 189 # Andrew Gallant (BurntSushi) start = "2019-07-07" end = "2026-03-01" [[trusted.rustix]] criteria = "safe-to-deploy" user-id = 6825 # Dan Gohman (sunfishcode) start = "2021-10-29" end = "2026-03-01" [[trusted.ryu]] criteria = "safe-to-deploy" user-id = 3618 # David Tolnay (dtolnay) start = "2019-05-02" end = "2026-03-01" [[trusted.syn]] criteria = "safe-to-deploy" user-id = 3618 # David Tolnay (dtolnay) start = "2019-03-01" end = "2026-03-01" [[trusted.typeid]] criteria = "safe-to-deploy" user-id = 3618 # David Tolnay (dtolnay) start = "2024-05-13" end = "2026-03-01" systemd-journal-logger-2.2.2/supply-chain/config.toml000064400000000000000000000035411046102023000210250ustar 00000000000000 # cargo-vet config file [cargo-vet] version = "0.10" [imports.bytecode-alliance] url = "https://raw.githubusercontent.com/bytecodealliance/wasmtime/main/supply-chain/audits.toml" [imports.embark-studios] url = "https://raw.githubusercontent.com/EmbarkStudios/rust-ecosystem/main/audits.toml" [imports.google] url = "https://raw.githubusercontent.com/google/supply-chain/main/audits.toml" [imports.mozilla] url = "https://raw.githubusercontent.com/mozilla/supply-chain/main/audits.toml" [imports.swsnr] url = "https://codeberg.org/swsnr/rust-supply-chain/raw/branch/main/audits.toml" [policy.systemd-journal-logger] audit-as-crates-io = false [[exemptions.console]] version = "0.15.10" criteria = "safe-to-run" [[exemptions.once_cell]] version = "1.20.2" criteria = "safe-to-run" [[exemptions.serde_fmt]] version = "1.0.3" criteria = "safe-to-deploy" [[exemptions.similar]] version = "2.7.0" criteria = "safe-to-run" [[exemptions.similar-asserts]] version = "1.6.1" criteria = "safe-to-run" [[exemptions.sval]] version = "2.14.0" criteria = "safe-to-deploy" [[exemptions.sval_buffer]] version = "2.14.0" criteria = "safe-to-deploy" [[exemptions.sval_dynamic]] version = "2.14.0" criteria = "safe-to-deploy" [[exemptions.sval_fmt]] version = "2.14.0" criteria = "safe-to-deploy" [[exemptions.sval_json]] version = "2.14.0" criteria = "safe-to-deploy" [[exemptions.sval_nested]] version = "2.14.0" criteria = "safe-to-deploy" [[exemptions.sval_ref]] version = "2.14.0" criteria = "safe-to-deploy" [[exemptions.sval_serde]] version = "2.14.0" criteria = "safe-to-deploy" [[exemptions.value-bag]] version = "1.10.0" criteria = "safe-to-deploy" [[exemptions.value-bag-serde1]] version = "1.10.0" criteria = "safe-to-deploy" [[exemptions.value-bag-sval2]] version = "1.10.0" criteria = "safe-to-deploy" [[exemptions.zerocopy]] version = "0.7.35" criteria = "safe-to-run" systemd-journal-logger-2.2.2/supply-chain/imports.lock000064400000000000000000001200351046102023000212300ustar 00000000000000 # cargo-vet imports lock [[publisher.erased-serde]] version = "0.4.5" when = "2024-05-14" user-id = 3618 user-login = "dtolnay" user-name = "David Tolnay" [[publisher.libc]] version = "0.2.153" when = "2024-01-31" user-id = 51017 user-login = "JohnTitor" user-name = "Yuki Okushi" [[publisher.linux-raw-sys]] version = "0.9.3" when = "2025-03-14" user-id = 6825 user-login = "sunfishcode" user-name = "Dan Gohman" [[publisher.memchr]] version = "2.7.4" when = "2024-06-14" user-id = 189 user-login = "BurntSushi" user-name = "Andrew Gallant" [[publisher.rustix]] version = "1.0.3" when = "2025-03-18" user-id = 6825 user-login = "sunfishcode" user-name = "Dan Gohman" [[publisher.ryu]] version = "1.0.20" when = "2025-03-04" user-id = 3618 user-login = "dtolnay" user-name = "David Tolnay" [[publisher.syn]] version = "2.0.100" when = "2025-03-09" user-id = 3618 user-login = "dtolnay" user-name = "David Tolnay" [[publisher.typeid]] version = "1.0.3" when = "2025-03-04" user-id = 3618 user-login = "dtolnay" user-name = "David Tolnay" [[publisher.unicode-segmentation]] version = "1.12.0" when = "2024-09-13" user-id = 1139 user-login = "Manishearth" user-name = "Manish Goregaokar" [[audits.bytecode-alliance.audits.bitflags]] who = "Jamey Sharp " criteria = "safe-to-deploy" delta = "2.1.0 -> 2.2.1" notes = """ This version adds unsafe impls of traits from the bytemuck crate when built with that library enabled, but I believe the impls satisfy the documented safety requirements for bytemuck. The other changes are minor. """ [[audits.bytecode-alliance.audits.bitflags]] who = "Alex Crichton " criteria = "safe-to-deploy" delta = "2.3.2 -> 2.3.3" notes = """ Nothing outside the realm of what one would expect from a bitflags generator, all as expected. """ [[audits.bytecode-alliance.audits.bitflags]] who = "Alex Crichton " criteria = "safe-to-deploy" delta = "2.4.1 -> 2.6.0" notes = """ Changes in how macros are invoked and various bits and pieces of macro-fu. Otherwise no major changes and nothing dealing with `unsafe`. """ [[audits.bytecode-alliance.audits.errno]] who = "Dan Gohman " criteria = "safe-to-deploy" version = "0.3.0" notes = "This crate uses libc and windows-sys APIs to get and set the raw OS error value." [[audits.bytecode-alliance.audits.errno]] who = "Dan Gohman " criteria = "safe-to-deploy" delta = "0.3.0 -> 0.3.1" notes = "Just a dependency version bump and a bug fix for redox" [[audits.bytecode-alliance.audits.errno]] who = "Dan Gohman " criteria = "safe-to-deploy" delta = "0.3.9 -> 0.3.10" [[audits.bytecode-alliance.audits.itoa]] who = "Dan Gohman " criteria = "safe-to-deploy" delta = "1.0.11 -> 1.0.14" [[audits.bytecode-alliance.audits.libc]] who = "Alex Crichton " criteria = "safe-to-deploy" delta = "0.2.153 -> 0.2.158" notes = "More platforms, more definitions, more headers, it's still just `libc`" [[audits.bytecode-alliance.audits.libc]] who = "Dan Gohman " criteria = "safe-to-deploy" delta = "0.2.158 -> 0.2.161" [[audits.bytecode-alliance.audits.libc]] who = "Alex Crichton " criteria = "safe-to-deploy" delta = "0.2.161 -> 0.2.171" notes = """ Lots of unsafe, but that's par for the course with libc, it's all FFI type definitions updates/adjustments/etc. """ [audits.embark-studios.audits] [[audits.google.audits.bitflags]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" version = "1.3.2" notes = """ Security review of earlier versions of the crate can be found at (Google-internal, sorry): go/image-crate-chromium-security-review The crate exposes a function marked as `unsafe`, but doesn't use any `unsafe` blocks (except for tests of the single `unsafe` function). I think this justifies marking this crate as `ub-risk-1`. Additional review comments can be found at https://crrev.com/c/4723145/31 """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.bitflags]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" delta = "2.6.0 -> 2.8.0" notes = "No changes related to `unsafe impl ... bytemuck` pieces from `src/external.rs`." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.bitflags]] who = "Daniel Cheng " criteria = "safe-to-deploy" delta = "2.8.0 -> 2.9.0" notes = "Adds a straightforward clear() function, but no new unsafe code." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.bstr]] who = "danakj " criteria = "safe-to-deploy" version = "1.10.0" notes = """ WARNING: This certification is a result of a **partial** audit. The `unicode` feature has **not** been audited. The unicode feature has soundness that depends on the correctness of regex automata that are shipped as binary blobs. They have not been reviewed here.Ability to track partial audits is tracked in https://github.com/mozilla/cargo-vet/issues/380. """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.bstr]] who = "Adrian Taylor " criteria = "safe-to-deploy" delta = "1.10.0 -> 1.11.0" notes = "Changes two unsafe blocks to use core::mem::align_of instead of core::mem::size_of which shouldn't differ on mainstream platforms." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.bstr]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" delta = "1.11.0 -> 1.11.1" notes = "This release just excludes Unicode data files from being published to crates.io" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.bstr]] who = "Dustin J. Mitchell " criteria = "safe-to-deploy" delta = "1.11.1 -> 1.11.3" notes = "No unsafe changes" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.byteorder]] who = "danakj " criteria = "safe-to-deploy" version = "1.5.0" notes = "Unsafe review in https://crrev.com/c/5838022" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.cfg-if]] who = "George Burgess IV " criteria = "safe-to-deploy" version = "1.0.0" aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" [[audits.google.audits.getrandom]] who = "Android Legacy" criteria = "safe-to-run" version = "0.2.2" aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" [[audits.google.audits.getrandom]] who = "David Koloski " criteria = "safe-to-deploy" delta = "0.2.2 -> 0.2.12" notes = "Audited at https://fxrev.dev/932979" aggregated-from = "https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/third_party/rust_crates/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.getrandom]] who = "Adrian Taylor " criteria = "safe-to-run" delta = "0.2.12 -> 0.2.14" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.getrandom]] who = "danakj " criteria = "safe-to-run" delta = "0.2.14 -> 0.2.15" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.itoa]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" version = "1.0.10" notes = ''' I grepped for \"crypt\", \"cipher\", \"fs\", \"net\" - there were no hits. There are a few places where `unsafe` is used. Unsafe review notes can be found in https://crrev.com/c/5350697. Version 1.0.1 of this crate has been added to Chromium in https://crrev.com/c/3321896. ''' aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.itoa]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" delta = "1.0.10 -> 1.0.11" notes = """ Straightforward diff between 1.0.10 and 1.0.11 - only 3 commits: * Bumping up the version * A touch up of comments * And my own PR to make `unsafe` blocks more granular: https://github.com/dtolnay/itoa/pull/42 """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.itoa]] who = "Daniel Cheng " criteria = "safe-to-deploy" delta = "1.0.14 -> 1.0.15" notes = "Only minor rustdoc changes." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.log]] who = "danakj " criteria = "safe-to-deploy" version = "0.4.22" notes = """ Unsafe review in https://docs.google.com/document/d/1IXQbD1GhTRqNHIGxq6yy7qHqxeO4CwN5noMFXnqyDIM/edit?usp=sharing Unsafety is generally very well-documented, with one exception, which we describe in the review doc. """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.log]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" delta = "0.4.22 -> 0.4.25" notes = "No impact on `unsafe` usage in `lib.rs`." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.ppv-lite86]] who = "danakj@chromium.org" criteria = "safe-to-run" version = "0.2.17" notes = """ Reviewed in https://crrev.com/c/5171063 Previously reviewed during security review and the audit is grandparented in. """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.ppv-lite86]] who = "danakj " criteria = "safe-to-run" delta = "0.2.17 -> 0.2.20" notes = "Using zerocopy to reduce unsafe usage." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" version = "1.0.78" notes = """ Grepped for \"crypt\", \"cipher\", \"fs\", \"net\" - there were no hits (except for a benign \"fs\" hit in a doc comment) Notes from the `unsafe` review can be found in https://crrev.com/c/5385745. """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "Adrian Taylor " criteria = "safe-to-deploy" delta = "1.0.78 -> 1.0.79" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "Adrian Taylor " criteria = "safe-to-deploy" delta = "1.0.79 -> 1.0.80" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "Dustin J. Mitchell " criteria = "safe-to-deploy" delta = "1.0.80 -> 1.0.81" notes = "Comment changes only" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "danakj " criteria = "safe-to-deploy" delta = "1.0.81 -> 1.0.82" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "Dustin J. Mitchell " criteria = "safe-to-deploy" delta = "1.0.82 -> 1.0.83" notes = "Substantive change is replacing String with Box, saving memory." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" delta = "1.0.83 -> 1.0.84" notes = "Only doc comment changes in `src/lib.rs`." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "danakj@chromium.org" criteria = "safe-to-deploy" delta = "1.0.84 -> 1.0.85" notes = "Test-only changes." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" delta = "1.0.85 -> 1.0.86" notes = """ Comment-only changes in `build.rs`. Reordering of `Cargo.toml` entries. Just bumping up the version number in `lib.rs`. Config-related changes in `test_size.rs`. """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "danakj " criteria = "safe-to-deploy" delta = "1.0.86 -> 1.0.87" notes = "No new unsafe interactions." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.proc-macro2]] who = "Liza Burakova // // 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.2/tests/init_with_extra_fields.rs000064400000000000000000000017431046102023000225100ustar 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.2/tests/journal.rs000064400000000000000000000100371046102023000174270ustar 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.2/tests/journal_stream.rs000064400000000000000000000066161046102023000210120ustar 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.2/tests/log_to_journal.rs000064400000000000000000000152311046102023000207730ustar 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.2/tests/log_with_extra_fields.rs000064400000000000000000000023271046102023000223250ustar 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)); }