Skip to content

Commit

Permalink
Detach from lazy_static, use std::sync::OnceLock instead
Browse files Browse the repository at this point in the history
  • Loading branch information
emabee committed Mar 1, 2024
1 parent 9bd6241 commit 98f1e9a
Show file tree
Hide file tree
Showing 10 changed files with 58 additions and 52 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci_test.yml
Expand Up @@ -57,7 +57,7 @@ jobs:
strategy:
matrix:
os: [ ubuntu-latest, windows-latest, macos-latest ]
rust: [ stable, 1.67.1 ]
rust: [ stable, 1.70.0 ]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -5,6 +5,10 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.27.5-unpublished] - 2024-xx-xx

Detach from `lazy_static`, use `std::sync::OnceLock` instead.

## [0.27.4] - 2024-01-20

Add ability to omit the basename cleanly, without leading underscore
Expand Down
5 changes: 2 additions & 3 deletions Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "flexi_logger"
version = "0.27.4"
version = "0.27.5-unpublished"
authors = ["emabee <meinolf.block@sap.com>"]
categories = ["development-tools::debugging"]
description = """
Expand All @@ -15,7 +15,7 @@ keywords = ["file", "logger"]
license = "MIT OR Apache-2.0"
readme = "README.md"
repository = "https://github.com/emabee/flexi_logger"
rust-version = "1.67.1"
rust-version = "1.70.0"

[lib]
doctest = false
Expand Down Expand Up @@ -48,7 +48,6 @@ crossbeam-queue = { version = "0.3", optional = true }
flate2 = { version = "1.0", optional = true }
glob = "0.3"
hostname = { version = "0.3", optional = true }
lazy_static = "1.4"
log = { version = "0.4", features = ["std"] }
notify-debouncer-mini = { version = "0.3", optional = true, default-features = false }
regex = { version = "1.1", optional = true }
Expand Down
3 changes: 1 addition & 2 deletions README.md
Expand Up @@ -60,8 +60,7 @@ See

## Minimal rust version

The minimal supported rust version is currently "1.67.1",
due to a change in a patch version of a dependency.
The minimal supported rust version is currently "1.70.0".

## Crate Features

Expand Down
6 changes: 3 additions & 3 deletions scripts/qualify.rs
Expand Up @@ -48,8 +48,8 @@ fn main() {

// Build in important variants
std::fs::remove_file("Cargo.lock").ok();
run_command!("cargo +1.67.1 build --no-default-features");
run_command!("cargo +1.67.1 build --all-features");
run_command!("cargo +1.70.0 build --no-default-features");
run_command!("cargo +1.70.0 build --all-features");

std::fs::remove_file("Cargo.lock").ok();
run_command!("cargo build");
Expand All @@ -67,7 +67,7 @@ fn main() {
run_command!("cargo +nightly clippy --all-targets --all-features -- -D warnings");

// Run tests in important variants
run_command!("cargo +1.67.1 test --all-features");
run_command!("cargo +1.70.0 test --all-features");
run_command!("cargo test --release --all-features");
run_command!("cargo test --no-default-features");
run_command!("cargo test --release");
Expand Down
41 changes: 21 additions & 20 deletions src/deferred_now.rs
Expand Up @@ -4,7 +4,7 @@ use chrono::{
};
#[cfg(feature = "syslog_writer")]
use chrono::{Datelike, Timelike};
use std::sync::{Arc, Mutex};
use std::sync::{Mutex, OnceLock};

/// Deferred timestamp creation.
///
Expand Down Expand Up @@ -116,41 +116,42 @@ impl<'a> DeferredNow {
/// Panics if called too late, i.e., if [`DeferredNow::now`] was already called before on
/// any instance of `DeferredNow`.
pub fn force_utc() {
let mut guard = FORCE_UTC.lock().unwrap();
match *guard {
let mut cfg_force_utc = cfg_force_utc().lock().unwrap();
match *cfg_force_utc {
Some(false) => {
panic!("offset is already initialized not to enforce UTC");
}
Some(true) => {
// is already set, nothing to do
}
None => *guard = Some(true),
None => *cfg_force_utc = Some(true),
}
}

#[allow(dead_code)]
pub(crate) fn set_force_utc(b: bool) {
let mut guard = FORCE_UTC.lock().unwrap();
*guard = Some(b);
}
}

lazy_static::lazy_static! {
static ref FORCE_UTC: Arc<Mutex<Option<bool>>> =
Arc::new(Mutex::new(None));
fn cfg_force_utc() -> &'static Mutex<Option<bool>> {
static CFG_FORCE_UTC: OnceLock<Mutex<Option<bool>>> = OnceLock::new();
CFG_FORCE_UTC.get_or_init(|| Mutex::new(None))
}

fn use_utc() -> bool {
let mut force_utc_guard = FORCE_UTC.lock().unwrap();
if let Some(true) = *force_utc_guard {
let mut cfg_force_utc = cfg_force_utc().lock().unwrap();
if let Some(true) = *cfg_force_utc {
true
} else {
if force_utc_guard.is_none() {
*force_utc_guard = Some(false);
if cfg_force_utc.is_none() {
*cfg_force_utc = Some(false);
}
false
}
}

#[cfg(test)]
pub(crate) fn set_force_utc(b: bool) {
let mut cfg_force_utc = cfg_force_utc().lock().unwrap();
*cfg_force_utc = Some(b);
}

#[cfg(test)]
mod test {
use crate::DeferredNow;
Expand Down Expand Up @@ -219,7 +220,7 @@ mod test {
#[cfg(feature = "syslog_writer")]
{
log::info!("test rfc3164");
super::DeferredNow::set_force_utc(true);
super::set_force_utc(true);
let (mut dn1, mut dn2) = get_deferred_nows();
assert_eq!("Apr 29 13:14:15", &dn1.format_rfc3164());
assert_eq!("Apr 29 12:14:15", &dn2.format_rfc3164());
Expand All @@ -228,13 +229,13 @@ mod test {
log::info!("test rfc3339");
{
// with local timestamps, offsets ≠ 0 are printed (except in Greenwich time zone):
super::DeferredNow::set_force_utc(false);
super::set_force_utc(false);
let (mut dn1, mut dn2) = get_deferred_nows();
log::info!("2021-04-29T15:14:15.678+02:00, {}", &dn1.format_rfc3339());
log::info!("2021-04-29T14:14:15.678+02:00, {}", &dn2.format_rfc3339());

// with utc, the timestamps are normalized to offset 0
super::DeferredNow::set_force_utc(true);
super::set_force_utc(true);
let (mut dn1, mut dn2) = get_deferred_nows();
assert_eq!("2021-04-29T13:14:15.678+00:00", &dn1.format_rfc3339());
assert_eq!("2021-04-29T12:14:15.678+00:00", &dn2.format_rfc3339());
Expand Down
26 changes: 13 additions & 13 deletions src/formats.rs
Expand Up @@ -2,7 +2,10 @@ use crate::DeferredNow;
use log::Record;
#[cfg(feature = "colors")]
use nu_ansi_term::{Color, Style};
use std::thread;
use std::{
sync::{OnceLock, RwLock},
thread,
};

/// Time stamp format that is used by the provided format functions.
pub const TS_DASHES_BLANK_COLONS_DOT_BLANK: &str = "%Y-%m-%d %H:%M:%S%.6f %:z";
Expand Down Expand Up @@ -220,7 +223,7 @@ pub fn colored_with_thread(
#[cfg(feature = "colors")]
#[must_use]
pub fn style(level: log::Level) -> Style {
let palette = &*(PALETTE.read().unwrap());
let palette = &*(palette().read().unwrap());
match level {
log::Level::Error => palette.error,
log::Level::Warn => palette.warn,
Expand All @@ -231,26 +234,23 @@ pub fn style(level: log::Level) -> Style {
}

#[cfg(feature = "colors")]
lazy_static::lazy_static! {
static ref PALETTE: std::sync::RwLock<Palette> = std::sync::RwLock::new(Palette::default());
fn palette() -> &'static RwLock<Palette> {
static PALETTE: OnceLock<RwLock<Palette>> = OnceLock::new();
PALETTE.get_or_init(|| RwLock::new(Palette::default()))
}

// Overwrites the default PALETTE value either from the environment, if set,
// or from the parameter, if filled.
// Returns an error if parsing failed.
#[cfg(feature = "colors")]
pub(crate) fn set_palette(input: &Option<String>) -> Result<(), std::num::ParseIntError> {
match std::env::var_os("FLEXI_LOGGER_PALETTE") {
Some(ref env_osstring) => {
*(PALETTE.write().unwrap()) = Palette::from(env_osstring.to_string_lossy().as_ref())?;
}
*(palette().write().unwrap()) = match std::env::var_os("FLEXI_LOGGER_PALETTE") {
Some(ref env_osstring) => Palette::from(env_osstring.to_string_lossy().as_ref()),
None => match input {
Some(ref input_string) => {
*(PALETTE.write().unwrap()) = Palette::from(input_string)?;
}
None => {}
Some(ref input_string) => Palette::from(input_string),
None => return Ok(()),
},
}
}?;
Ok(())
}

Expand Down
19 changes: 11 additions & 8 deletions src/util.rs
@@ -1,10 +1,12 @@
use crate::logger::ErrorChannel;
use crate::{DeferredNow, FormatFunction};
use log::Record;
use std::cell::RefCell;
use std::io::Write;
use std::path::Path;
use std::sync::RwLock;
use std::{
cell::RefCell,
io::Write,
path::Path,
sync::{OnceLock, RwLock},
};

#[cfg(test)]
use std::io::Cursor;
Expand Down Expand Up @@ -69,12 +71,13 @@ pub(crate) fn eprint_msg(error_code: ErrorCode, msg: &str) {
try_to_write(&s);
}

lazy_static::lazy_static! {
pub(crate) static ref ERROR_CHANNEL: RwLock<ErrorChannel> = RwLock::new(ErrorChannel::default());
fn error_channel() -> &'static RwLock<ErrorChannel> {
static ERROR_CHANNEL: OnceLock<RwLock<ErrorChannel>> = OnceLock::new();
ERROR_CHANNEL.get_or_init(|| RwLock::new(ErrorChannel::default()))
}

pub(crate) fn set_error_channel(channel: ErrorChannel) {
match ERROR_CHANNEL.write() {
match error_channel().write() {
Ok(mut guard) => {
*guard = channel;
}
Expand All @@ -85,7 +88,7 @@ pub(crate) fn set_error_channel(channel: ErrorChannel) {
}

fn try_to_write(s: &str) {
match &*(ERROR_CHANNEL.read().unwrap()) {
match &*(error_channel().read().unwrap()) {
ErrorChannel::StdErr => {
eprintln!("{s}");
}
Expand Down
2 changes: 1 addition & 1 deletion tests/test_specfile.rs
Expand Up @@ -45,7 +45,7 @@ mod a {
std::fs::rename(&specfile, old_name).unwrap();
let mut file = std::fs::OpenOptions::new()
.create(true)
.write(true)
.append(true)
.open(&specfile)
.unwrap();
file.write_all(
Expand Down
2 changes: 1 addition & 1 deletion tests/test_trc.rs
Expand Up @@ -50,7 +50,7 @@ mod a {
std::fs::rename(&specfile, old_name).unwrap();
let mut file = std::fs::OpenOptions::new()
.create(true)
.write(true)
.append(true)
.open(&specfile)
.unwrap();
file.write_all(
Expand Down

2 comments on commit 98f1e9a

@hasezoey
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rust-version = "1.70.0"

[0.27.5-unpublished] - 2024-xx-xx

i would recommend not doing this as a patch, as increasing the MSRV could be breaking

@emabee
Copy link
Owner Author

@emabee emabee commented on 98f1e9a Mar 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed :-)

Please sign in to comment.