Skip to content

Commit

Permalink
refactor: improve layout (#11)
Browse files Browse the repository at this point in the history
Co-authored-by: tison <[email protected]>
  • Loading branch information
andylokandy and tisonkun committed Aug 1, 2024
1 parent 4be7d02 commit 4fd68a2
Show file tree
Hide file tree
Showing 10 changed files with 116 additions and 113 deletions.
12 changes: 5 additions & 7 deletions examples/fn_layout_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use log::LevelFilter;
use logforth::append;
use logforth::filter;
use logforth::filter::FilterResult;
use logforth::layout;
use logforth::logger::Dispatch;
use logforth::logger::Logger;

Expand All @@ -24,18 +25,15 @@ fn main() {
.dispatch(
Dispatch::new()
.filter(filter::BoxDyn::new(|metadata: &log::Metadata| {
if metadata.level() <= LevelFilter::Info {
if metadata.level() > LevelFilter::Info {
FilterResult::Accept
} else {
FilterResult::Reject
}
}))
// .layout(layout::BoxDyn::new(|record: &log::Record| {
// let args = format_args!("[box dyn] {}", record.args());
// Ok(record.to_builder().args(args).build())
// // ...or
// // anyhow::bail!("boom: {}", message)
// }))
.layout(layout::CustomLayout::new(|record, f| {
f(format_args!("[system alert] {}", record.args()))
}))
.append(append::Stdout),
)
.apply()
Expand Down
4 changes: 2 additions & 2 deletions src/append/boxdyn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use log::Record;
use crate::append::Append;
use crate::append::AppendImpl;
use crate::filter::FilterImpl;
use crate::layout::LayoutImpl;
use crate::layout::Layout;

pub struct BoxDyn(Box<dyn Append + Send + Sync>);

Expand All @@ -44,7 +44,7 @@ impl Append for BoxDyn {
(*self.0).flush()
}

fn default_layout(&self) -> LayoutImpl {
fn default_layout(&self) -> Layout {
(*self.0).default_layout()
}

Expand Down
8 changes: 4 additions & 4 deletions src/append/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use crate::dynlog::DynLog;
use crate::filter::FilterImpl;
use crate::layout;
use crate::layout::LayoutImpl;
use crate::layout::Layout;
pub use boxdyn::*;
#[cfg(feature = "fastrace")]
pub use fastrace::*;
Expand All @@ -39,8 +39,8 @@ pub trait Append {

/// Default layout to use when [Dispatch][crate::logger::Dispatch] does not configure a
/// preferred layout.
fn default_layout(&self) -> LayoutImpl {
LayoutImpl::Identical(layout::Identical)
fn default_layout(&self) -> Layout {
Layout::Identical(layout::Identical)
}

/// Default filters associated to this append. [log::Log] is mixed with
Expand Down Expand Up @@ -89,7 +89,7 @@ impl Append for AppendImpl {
}
}

fn default_layout(&self) -> LayoutImpl {
fn default_layout(&self) -> Layout {
match self {
AppendImpl::BoxDyn(append) => append.default_layout(),
AppendImpl::DynLog(append) => append.default_layout(),
Expand Down
52 changes: 0 additions & 52 deletions src/layout/boxdyn.rs

This file was deleted.

59 changes: 59 additions & 0 deletions src/layout/custom.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright 2024 tison <[email protected]>
//
// 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.

use std::fmt::{Arguments, Debug, Formatter};

use crate::layout::Layout;

pub struct CustomLayout {
#[allow(clippy::type_complexity)]
f: Box<
dyn Fn(&log::Record, &dyn Fn(Arguments) -> anyhow::Result<()>) -> anyhow::Result<()>
+ Send
+ Sync
+ 'static,
>,
}

impl Debug for CustomLayout {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "CustomLayout {{ ... }}")
}
}

impl CustomLayout {
pub fn new(
layout: impl Fn(&log::Record, &dyn Fn(Arguments) -> anyhow::Result<()>) -> anyhow::Result<()>
+ Send
+ Sync
+ 'static,
) -> Self {
CustomLayout {
f: Box::new(layout),
}
}

pub fn format<F>(&self, record: &log::Record, f: &F) -> anyhow::Result<()>
where
F: Fn(Arguments) -> anyhow::Result<()>,
{
(self.f)(record, f)
}
}

impl From<CustomLayout> for Layout {
fn from(layout: CustomLayout) -> Self {
Layout::Custom(layout)
}
}
14 changes: 7 additions & 7 deletions src/layout/identical.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
use crate::layout::Layout;
use crate::layout::LayoutImpl;
use std::fmt::Arguments;

#[derive(Debug, Default, Clone, Copy)]
pub struct Identical;

impl Layout for Identical {
fn format<F>(&self, record: &log::Record, f: F) -> anyhow::Result<()>
impl Identical {
pub fn format<F>(&self, record: &log::Record, f: &F) -> anyhow::Result<()>
where
F: Fn(&log::Record) -> anyhow::Result<()>,
F: Fn(Arguments) -> anyhow::Result<()>,
{
f(record)
f(*record.args())
}
}

impl From<Identical> for LayoutImpl {
impl From<Identical> for Layout {
fn from(layout: Identical) -> Self {
LayoutImpl::Identical(layout)
Layout::Identical(layout)
}
}
34 changes: 18 additions & 16 deletions src/layout/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,46 +12,48 @@
// See the License for the specific language governing permissions and
// limitations under the License.

// pub use boxdyn::BoxDyn;
pub use custom::CustomLayout;
pub use identical::Identical;
pub use kv_display::KvDisplay;
#[cfg(feature = "json")]
pub use simple_json::SimpleJson;
pub use simple_text::SimpleText;

// mod boxdyn;
mod custom;
mod identical;
mod kv_display;
#[cfg(feature = "json")]
mod simple_json;
mod simple_text;

pub trait Layout {
fn format<F>(&self, record: &log::Record, f: F) -> anyhow::Result<()>
where
F: Fn(&log::Record) -> anyhow::Result<()>;
}

#[derive(Debug)]
pub enum LayoutImpl {
// BoxDyn(BoxDyn),
pub enum Layout {
Identical(Identical),
SimpleText(SimpleText),
#[cfg(feature = "json")]
SimpleJson(SimpleJson),
Custom(CustomLayout),
}

impl Layout for LayoutImpl {
fn format<F>(&self, record: &log::Record, f: F) -> anyhow::Result<()>
impl Layout {
pub fn format<F>(&self, record: &log::Record, f: &F) -> anyhow::Result<()>
where
F: Fn(&log::Record) -> anyhow::Result<()>,
{
match self {
// LayoutImpl::BoxDyn(layout) => layout.format_record(record),
LayoutImpl::Identical(layout) => layout.format(record, f),
LayoutImpl::SimpleText(layout) => layout.format(record, f),
Layout::Identical(layout) => {
layout.format(record, &|args| f(&record.to_builder().args(args).build()))
}
Layout::SimpleText(layout) => {
layout.format(record, &|args| f(&record.to_builder().args(args).build()))
}
#[cfg(feature = "json")]
LayoutImpl::SimpleJson(layout) => layout.format(record, f),
Layout::SimpleJson(layout) => {
layout.format(record, &|args| f(&record.to_builder().args(args).build()))
}
Layout::Custom(layout) => {
layout.format(record, &|args| f(&record.to_builder().args(args).build()))
}
}
}
}
14 changes: 7 additions & 7 deletions src/layout/simple_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt::Arguments;
use std::path::Path;
use std::time::SystemTime;

Expand All @@ -22,7 +23,6 @@ use serde_json::Map;
use serde_json::Value;

use crate::layout::Layout;
use crate::layout::LayoutImpl;

#[derive(Default, Debug, Clone)]
pub struct SimpleJson;
Expand Down Expand Up @@ -55,10 +55,10 @@ struct RecordLine<'a> {
kvs: Map<String, Value>,
}

impl Layout for SimpleJson {
fn format<F>(&self, record: &Record, f: F) -> anyhow::Result<()>
impl SimpleJson {
pub fn format<F>(&self, record: &Record, f: &F) -> anyhow::Result<()>
where
F: Fn(&Record) -> anyhow::Result<()>,
F: Fn(Arguments) -> anyhow::Result<()>,
{
let mut kvs = Map::new();
let mut visitor = KvCollector { kvs: &mut kvs };
Expand All @@ -80,12 +80,12 @@ impl Layout for SimpleJson {
};

let text = serde_json::to_string(&record_line)?;
f(&record.to_builder().args(format_args!("{text}",)).build())
f(format_args!("{text}"))
}
}

impl From<SimpleJson> for LayoutImpl {
impl From<SimpleJson> for Layout {
fn from(layout: SimpleJson) -> Self {
LayoutImpl::SimpleJson(layout)
Layout::SimpleJson(layout)
}
}
21 changes: 9 additions & 12 deletions src/layout/simple_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt::Arguments;
use std::path::Path;
use std::time::SystemTime;

Expand All @@ -22,7 +23,6 @@ use log::Level;

use crate::layout::kv_display::KvDisplay;
use crate::layout::Layout;
use crate::layout::LayoutImpl;

#[derive(Default, Debug, Clone)]
pub struct SimpleText {
Expand Down Expand Up @@ -50,10 +50,10 @@ impl Default for ColoredLevel {
}
}

impl Layout for SimpleText {
fn format<F>(&self, record: &log::Record, f: F) -> anyhow::Result<()>
impl SimpleText {
pub fn format<F>(&self, record: &log::Record, f: &F) -> anyhow::Result<()>
where
F: Fn(&log::Record) -> anyhow::Result<()>,
F: Fn(Arguments) -> anyhow::Result<()>,
{
let color = match record.level() {
Level::Error => self.colors.error,
Expand All @@ -75,17 +75,14 @@ impl Layout for SimpleText {
let message = record.args();
let kvs = KvDisplay::new(record.key_values());

f(&record
.to_builder()
.args(format_args!(
"{time} {level:>5} {module}: {file}:{line} {message}{kvs}"
))
.build())
f(format_args!(
"{time} {level:>5} {module}: {file}:{line} {message}{kvs}"
))
}
}

impl From<SimpleText> for LayoutImpl {
impl From<SimpleText> for Layout {
fn from(layout: SimpleText) -> Self {
LayoutImpl::SimpleText(layout)
Layout::SimpleText(layout)
}
}
Loading

0 comments on commit 4fd68a2

Please sign in to comment.