Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add options to use UTC timestamps #46

Merged
merged 6 commits into from
Dec 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 16 additions & 12 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
---
name: ci

on: [pull_request, push]
on:
pull_request:
push:
branches:
- master

env:
# Just a reassurance to mitigate sudden network connection problems
Expand Down Expand Up @@ -32,7 +36,7 @@ jobs:
rust-test:
runs-on: ${{ matrix.os }}

continue-on-error: ${{ matrix.toolchain != 'stable' || (matrix.os == 'macos-latest' && contains(matrix.features, 'timestamps')) }}
continue-on-error: ${{ matrix.toolchain != 'stable' }}

strategy:
matrix:
Expand All @@ -47,17 +51,17 @@ jobs:
- "threads"
- "timestamps"
- "stderr"
exclude:
- os: macos-latest
toolchain: stable
features: "timestamps"
include:
- {
os: ubuntu-latest,
toolchain: beta,
features: "colors,threads,timestamps",
}
- {
os: ubuntu-latest,
toolchain: nightly,
features: "colors,threads,timestamps,nightly",
}
- os: ubuntu-latest
toolchain: beta
features: "colors,threads,timestamps"
- os: ubuntu-latest
toolchain: nightly
features: "colors,threads,timestamps,nightly"

steps:
- uses: actions/checkout@v2
Expand Down
8 changes: 6 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "simple_logger"
version = "1.15.1"
version = "1.16.0"
license = "MIT"
authors = ["Sam Clements <sam@borntyping.co.uk>"]
description = "A logger that prints all messages with a readable output format"
Expand Down Expand Up @@ -33,5 +33,9 @@ name = "threads"
required-features = ["threads"]

[[example]]
name = "timestamps"
name = "timestamps_utc"
required-features = ["timestamps"]

[[example]]
name = "timestamps_local"
required-features = ["timestamps"]
7 changes: 7 additions & 0 deletions examples/timestamps_local.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use simple_logger::SimpleLogger;

fn main() {
SimpleLogger::new().with_local_timestamps().init().unwrap();

log::warn!("This is an example message.");
}
2 changes: 1 addition & 1 deletion examples/timestamps.rs → examples/timestamps_utc.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use simple_logger::SimpleLogger;

fn main() {
SimpleLogger::new().with_timestamps(true).init().unwrap();
SimpleLogger::new().with_utc_timestamps().init().unwrap();

log::warn!("This is an example message.");
}
105 changes: 86 additions & 19 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ const TIMESTAMP_FORMAT: &[FormatItem] = time::macros::format_description!(
"[year]-[month]-[day] [hour]:[minute]:[second],[subsecond digits:3]"
);

#[cfg(feature = "timestamps")]
#[derive(PartialEq)]
enum Timestamps {
None,
Local,
Utc,
}

/// Implements [`Log`] and a set of simple builder methods for configuration.
///
/// Use the various "builder" methods on this struct to configure the logger,
Expand All @@ -63,11 +71,11 @@ pub struct SimpleLogger {
#[cfg(feature = "threads")]
threads: bool,

/// Whether to include timestamps or not
/// Control how timestamps are displayed.
///
/// This field is only available if the `timestamps` feature is enabled.
#[cfg(feature = "timestamps")]
timestamps: bool,
timestamps: Timestamps,

/// Whether to use color output or not.
///
Expand Down Expand Up @@ -97,7 +105,7 @@ impl SimpleLogger {
threads: false,

#[cfg(feature = "timestamps")]
timestamps: true,
timestamps: Timestamps::Local,

#[cfg(feature = "colored")]
colors: true,
Expand Down Expand Up @@ -236,11 +244,51 @@ impl SimpleLogger {

/// Control whether timestamps are printed or not.
///
/// Timestamps will be displayed in the local timezone.
///
/// This method is only available if the `timestamps` feature is enabled.
#[must_use = "You must call init() to begin logging"]
#[cfg(feature = "timestamps")]
#[deprecated(
since = "1.16.0",
note = "Use [`with_local_timestamps`] or [`with_utc_timestamps`] instead. Will be removed in version 2.0.0."
)]
pub fn with_timestamps(mut self, timestamps: bool) -> SimpleLogger {
self.timestamps = timestamps;
if timestamps {
self.timestamps = Timestamps::Local
} else {
self.timestamps = Timestamps::None
}
self
}

/// Don't display any timestamps.
///
/// This method is only available if the `timestamps` feature is enabled.
#[must_use = "You must call init() to begin logging"]
#[cfg(feature = "timestamps")]
pub fn without_timestamps(mut self) -> SimpleLogger {
self.timestamps = Timestamps::None;
self
}

/// Display timestamps using the local timezone.
///
/// This method is only available if the `timestamps` feature is enabled.
#[must_use = "You must call init() to begin logging"]
#[cfg(feature = "timestamps")]
pub fn with_local_timestamps(mut self) -> SimpleLogger {
self.timestamps = Timestamps::Local;
self
}

/// Display timestamps using UTC.
///
/// This method is only available if the `timestamps` feature is enabled.
#[must_use = "You must call init() to begin logging"]
#[cfg(feature = "timestamps")]
pub fn with_utc_timestamps(mut self) -> SimpleLogger {
self.timestamps = Timestamps::Utc;
self
}

Expand Down Expand Up @@ -356,17 +404,17 @@ impl Log for SimpleLogger {

let timestamp = {
#[cfg(feature = "timestamps")]
if self.timestamps {
format!("{} ", OffsetDateTime::now_local().expect(concat!(
"Could not determine the UTC offset on this system. ",
"Possible causes are that the time crate does not implement \"local_offset_at\" ",
"on your system, or that you are running in a multi-threaded environment and ",
"the time crate is returning \"None\" from \"local_offset_at\" to avoid unsafe ",
"behaviour. See the time crate's documentation for more information. ",
"(https://time-rs.github.io/internal-api/time/index.html#feature-flags)"
)).format(&TIMESTAMP_FORMAT).unwrap())
} else {
"".to_string()
match self.timestamps {
Timestamps::None => "".to_string(),
Timestamps::Local => format!("{} ", OffsetDateTime::now_local().expect(concat!(
"Could not determine the UTC offset on this system. ",
"Possible causes are that the time crate does not implement \"local_offset_at\" ",
"on your system, or that you are running in a multi-threaded environment and ",
"the time crate is returning \"None\" from \"local_offset_at\" to avoid unsafe ",
"behaviour. See the time crate's documentation for more information. ",
"(https://time-rs.github.io/internal-api/time/index.html#feature-flags)"
)).format(&TIMESTAMP_FORMAT).unwrap()),
Timestamps::Utc => format!("{} ", OffsetDateTime::now_utc().format(&TIMESTAMP_FORMAT).unwrap()),
}

#[cfg(not(feature = "timestamps"))]
Expand Down Expand Up @@ -496,12 +544,31 @@ mod test {

#[test]
#[cfg(feature = "timestamps")]
fn test_timestamps_defaults() {
let builder = SimpleLogger::new();
assert!(builder.timestamps == Timestamps::Local);
}

#[test]
#[cfg(feature = "timestamps")]
#[allow(deprecated)]
fn test_with_timestamps() {
let mut builder = SimpleLogger::new();
assert!(builder.timestamps == true);
let builder = SimpleLogger::new().with_timestamps(false);
assert!(builder.timestamps == Timestamps::None);
}

#[test]
#[cfg(feature = "timestamps")]
fn test_with_utc_timestamps() {
let builder = SimpleLogger::new().with_utc_timestamps();
assert!(builder.timestamps == Timestamps::Utc);
}

builder = builder.with_timestamps(false);
assert!(builder.timestamps == false);
#[test]
#[cfg(feature = "timestamps")]
fn test_with_local_timestamps() {
let builder = SimpleLogger::new().with_local_timestamps();
assert!(builder.timestamps == Timestamps::Local);
}

#[test]
Expand Down