Skip to content

Commit

Permalink
Rework LoggerHande::existing_log_files()
Browse files Browse the repository at this point in the history
- extend LogWriter
- extend impact of trigger_rotation
  • Loading branch information
emabee committed Sep 21, 2023
1 parent 089a583 commit 2786748
Show file tree
Hide file tree
Showing 16 changed files with 247 additions and 220 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ 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.0] - 2023-09-20

Revise, and modify the signature of, `LoggerHande::existing_log_files()` (version bump).

Extend the trait `LogWriter` with an optional method `rotate`.

Extend impact of `LoggerHande::trigger_rotation()` to all configured writers.

## [0.26.1] - 2023-09-19

Introduce new naming variants that work without `_rCURRENT` files: `Naming::TimestampsDirect`
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "flexi_logger"
version = "0.26.1"
version = "0.27.0"
authors = ["emabee <meinolf.block@sap.com>"]
categories = ["development-tools::debugging"]
description = """
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ and you use the ```log``` macros to write log lines from your code):

```toml
[dependencies]
flexi_logger = "0.26"
flexi_logger = "0.27"
log = "0.4"
```

Expand Down Expand Up @@ -69,15 +69,15 @@ Make use of the non-default features by specifying them in your `Cargo.toml`, e.

```toml
[dependencies]
flexi_logger = { version = "0.26", features = ["async", "specfile", "compress"] }
flexi_logger = { version = "0.27", features = ["async", "specfile", "compress"] }
log = "0.4"
```

or, to get the smallest footprint (and no colors), switch off even the default features:

```toml
[dependencies]
flexi_logger = { version = "0.26", default_features = false }
flexi_logger = { version = "0.27", default_features = false }
log = "0.4"
```

Expand Down
4 changes: 4 additions & 0 deletions src/file_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,10 @@ impl FileSpec {
self.directory.clone()
}

pub(crate) fn get_suffix(&self) -> Option<String> {
self.o_suffix.clone()
}

/// Derives a `PathBuf` from the spec and the given infix.
///
/// It is composed like this:
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ pub use crate::flexi_error::FlexiLoggerError;
pub use crate::formats::*;
pub use crate::log_specification::{LogSpecBuilder, LogSpecification, ModuleFilter};
pub use crate::logger::{Duplicate, ErrorChannel, Logger};
pub use crate::logger_handle::LoggerHandle;
pub use crate::logger_handle::{LogfileSelector, LoggerHandle};
pub use crate::parameters::{Age, Cleanup, Criterion, Naming};
pub(crate) use crate::write_mode::EffectiveWriteMode;
pub use crate::write_mode::{WriteMode, DEFAULT_BUFFER_CAPACITY, DEFAULT_FLUSH_INTERVAL};
Expand Down
87 changes: 78 additions & 9 deletions src/logger_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,14 +278,23 @@ impl LoggerHandle {
/// # Errors
///
/// `FlexiLoggerError::Poison` if some mutex is poisoned.
///
/// IO errors.
pub fn trigger_rotation(&self) -> Result<(), FlexiLoggerError> {
if let PrimaryWriter::Multi(ref mw) = &*self.writers_handle.primary_writer {
mw.trigger_rotation()?;
let mut result = if let PrimaryWriter::Multi(ref mw) = &*self.writers_handle.primary_writer
{
mw.trigger_rotation()
} else {
Ok(())
};

for blw in self.writers_handle.other_writers.values() {
let result2 = blw.rotate();
if result.is_ok() && result2.is_err() {
result = result2;
}
}
// for blw in self.writers_handle.other_writers.values() {
// let result2 = blw.trigger_rotation(); // todo is not (yet?) part of trait LogWriter
// }
Ok(())
result
}

/// Shutdown all participating writers.
Expand All @@ -308,14 +317,21 @@ impl LoggerHandle {

/// Returns the list of existing log files according to the current `FileSpec`.
///
/// The list includes the current log file and the compressed files, if they exist.
/// Depending on the given selector, the list may include the CURRENT log file
/// and the compressed files, if they exist.
/// The list is empty if the logger is not configured for writing to files.
///
/// # Errors
///
/// `FlexiLoggerError::Poison` if some mutex is poisoned.
pub fn existing_log_files(&self) -> Result<Vec<PathBuf>, FlexiLoggerError> {
let mut log_files = self.writers_handle.primary_writer.existing_log_files()?;
pub fn existing_log_files(
&self,
selector: &LogfileSelector,
) -> Result<Vec<PathBuf>, FlexiLoggerError> {
let mut log_files = self
.writers_handle
.primary_writer
.existing_log_files(selector)?;
log_files.sort();
Ok(log_files)
}
Expand Down Expand Up @@ -357,6 +373,59 @@ impl LoggerHandle {
}
}

/// Used in [`LoggerHandle::existing_log_files`].
///
/// Example:
///
/// ```rust
/// # use flexi_logger::{LogfileSelector,Logger};
/// # let logger_handle = Logger::try_with_env().unwrap().start().unwrap();
/// let all_log_files = logger_handle.existing_log_files(
/// &LogfileSelector::default()
/// .with_r_current()
/// .with_compressed_files()
/// );
/// ```
pub struct LogfileSelector {
pub(crate) with_plain_files: bool,
pub(crate) with_r_current: bool,
pub(crate) with_compressed_files: bool,
}
impl Default for LogfileSelector {
/// Selects plain log files without the `rCURRENT` file.
fn default() -> Self {
Self {
with_plain_files: true,
with_r_current: false,
with_compressed_files: false,
}
}
}
impl LogfileSelector {
/// Selects no file at all.
#[must_use]
pub fn none() -> Self {
Self {
with_plain_files: false,
with_r_current: false,
with_compressed_files: false,
}
}
/// Selects additionally the `rCURRENT` file.
#[must_use]
pub fn with_r_current(mut self) -> Self {
self.with_r_current = true;
self
}

/// Selects additionally the compressed log files.
#[must_use]
pub fn with_compressed_files(mut self) -> Self {
self.with_compressed_files = true;
self
}
}

#[derive(Clone)]
pub(crate) struct WritersHandle {
spec: Arc<RwLock<LogSpecification>>,
Expand Down
9 changes: 6 additions & 3 deletions src/primary_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{
filter::LogLineWriter,
logger::Duplicate,
writers::{FileLogWriter, LogWriter},
DeferredNow, FlexiLoggerError, FormatFunction, WriteMode,
DeferredNow, FlexiLoggerError, FormatFunction, LogfileSelector, WriteMode,
};
use log::Record;
use std::path::PathBuf;
Expand Down Expand Up @@ -115,9 +115,12 @@ impl PrimaryWriter {
}
}

pub fn existing_log_files(&self) -> Result<Vec<PathBuf>, FlexiLoggerError> {
pub fn existing_log_files(
&self,
selector: &LogfileSelector,
) -> Result<Vec<PathBuf>, FlexiLoggerError> {
match self {
Self::Multi(multi_writer) => multi_writer.existing_log_files(),
Self::Multi(multi_writer) => multi_writer.existing_log_files(selector),
_ => Ok(Vec::new()),
}
}
Expand Down
34 changes: 21 additions & 13 deletions src/primary_writer/multi_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{
logger::Duplicate,
util::{eprint_err, write_buffered, ErrorCode},
writers::{FileLogWriter, FileLogWriterBuilder, FileLogWriterConfig, LogWriter},
{DeferredNow, FlexiLoggerError, FormatFunction},
LogfileSelector, {DeferredNow, FlexiLoggerError, FormatFunction},
};
use log::Record;
use std::{
Expand Down Expand Up @@ -71,9 +71,27 @@ impl MultiWriter {
}
}
}
pub(crate) fn existing_log_files(&self) -> Result<Vec<PathBuf>, FlexiLoggerError> {
pub(crate) fn trigger_rotation(&self) -> Result<(), FlexiLoggerError> {
match (&self.o_file_writer, &self.o_other_writer) {
(None, None) => Ok(()),
(Some(ref w), None) => w.rotate(),
(None, Some(w)) => w.rotate(),
(Some(w1), Some(w2)) => {
let r1 = w1.rotate();
let r2 = w2.rotate();
match (r1, r2) {
(Ok(()), Ok(())) => Ok(()),
(Err(e), _) | (Ok(()), Err(e)) => Err(e),
}
}
}
}
pub(crate) fn existing_log_files(
&self,
selector: &LogfileSelector,
) -> Result<Vec<PathBuf>, FlexiLoggerError> {
if let Some(fw) = self.o_file_writer.as_ref() {
fw.existing_log_files()
fw.existing_log_files(selector)
} else {
Ok(Vec::new())
}
Expand All @@ -93,16 +111,6 @@ impl MultiWriter {
fn duplication_to_stdout(&self) -> Duplicate {
Duplicate::from(self.duplicate_stdout.load(Ordering::Relaxed))
}

pub(crate) fn trigger_rotation(&self) -> Result<(), FlexiLoggerError> {
if let Some(ref w) = &self.o_file_writer {
w.trigger_rotation()?;
}
// if let Some(w) = &self.o_other_writer {
// w.trigger_rotation(); // todo is not (yet?) part of trait LogWriter
// }
Ok(())
}
}

impl LogWriter for MultiWriter {
Expand Down
20 changes: 15 additions & 5 deletions src/writers/file_log_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ pub use self::config::FileLogWriterConfig;

use self::{config::RotationConfig, state::State, state_handle::StateHandle};
use crate::{
writers::LogWriter, DeferredNow, EffectiveWriteMode, FileSpec, FlexiLoggerError, FormatFunction,
writers::LogWriter, DeferredNow, EffectiveWriteMode, FileSpec, FlexiLoggerError,
FormatFunction, LogfileSelector,
};
use log::Record;
use std::path::PathBuf;
Expand Down Expand Up @@ -132,8 +133,10 @@ impl FileLogWriter {
/// # Errors
///
/// `FlexiLoggerError::Poison` if some mutex is poisoned.
pub fn trigger_rotation(&self) -> Result<(), FlexiLoggerError> {
self.state_handle.force_rotation()
///
/// IO errors.
pub fn rotate(&self) -> Result<(), FlexiLoggerError> {
self.state_handle.rotate()
}

/// Returns the list of existing log files according to the current `FileSpec`.
Expand All @@ -143,8 +146,11 @@ impl FileLogWriter {
/// # Errors
///
/// `FlexiLoggerError::Poison` if some mutex is poisoned.
pub fn existing_log_files(&self) -> Result<Vec<PathBuf>, FlexiLoggerError> {
self.state_handle.existing_log_files()
pub fn existing_log_files(
&self,
selector: &LogfileSelector,
) -> Result<Vec<PathBuf>, FlexiLoggerError> {
self.state_handle.existing_log_files(selector)
}
}

Expand All @@ -168,6 +174,10 @@ impl LogWriter for FileLogWriter {
self.reopen_outputfile()
}

fn rotate(&self) -> Result<(), FlexiLoggerError> {
self.state_handle.rotate()
}

fn validate_logs(&self, expected: &[(&'static str, &'static str, &'static str)]) {
self.state_handle.validate_logs(expected);
}
Expand Down

0 comments on commit 2786748

Please sign in to comment.