πŸ’¬ A couple of functions to make logging in Rust easier.

Overview

Rust logging β›”

πŸ’¬ A couple of functions to make logging in Rust easier.

Installation πŸ“¦

Just add the code of code.rs to your project.

You can copy/paste the code to your project here.

Usage πŸ“

This code provides the following functions:

  • 🟑 warn(): Prints a warning message.
  • πŸ”΄ error(): Prints an error message.
  • πŸ”΅ info(): Prints an information message.
  • 🟒 success(): Prints a success message.

Each function takes a single parameter, which is the message to be printed.

error("a command failed : hello"); 
info("executing command : hello");
warn("a command is about to fail : hello");
success("a command succeeded : hello");

Highlighting πŸ”

By default, the text after the colon is highlighted.

This can be disabled by setting the HIGHLIGHT constant to false.

const HIGHLIGHT: bool = false;

Icon connector πŸ”—

By default, the icon and the message are separated by an arrow ->

You can change this by setting the ICON_CONNECTOR constant to something else.

const ICON_CONNECTOR: &str = "πŸ”—";

Icons πŸ”

By default, the following icons are used:

Icon Function
[ x ] error()
[ i ] info()
[ v ] success()
[ ! ] warn()

You can change this by setting the following constants:

const ERROR_ICON: &str = "[ β›” ]";
const INFO_ICON: &str = "[ ℹ️ ]";
const SUCCESS_ICON: &str = "[ βœ… ]";
const WARNING_ICON: &str = "[ ⚠️ ]";

Copy/paste πŸ“‹

"; // connector between icon and message const ERROR_ICON: &str = "[ x ]"; // icon for errors const INFO_ICON: &str = "[ i ]"; // icon for informations const SUCCESS_ICON: &str = "[ v ]"; // icon for success const WARNING_ICON: &str = "[ ! ]"; // icon for warnings const HIGHLIGHT: bool = true; // should the text after ":" be highlighted // --------------- const RED: &str = "\x1b[91m"; const GREEN: &str = "\x1b[92m"; const YELLOW: &str = "\x1b[93m"; const CYAN: &str = "\x1b[96m"; const WHITE: &str = "\x1b[97m"; const RESET: &str = "\x1b[0m"; const BG_RED: &str = "\x1b[41m"; const BG_CYAN: &str = "\x1b[46m"; const BG_GREEN: &str = "\x1b[42m"; const BG_YELLOW: &str = "\x1b[43m"; fn warn(msg: &str) { let msg = String::from(msg); let mut msg_vec = msg.split(":").collect::>(); println!( "{}{} {} {}{}{}", YELLOW, WARNING_ICON, ICON_CONNECTOR, msg_vec.remove(0), if msg_vec.len() > 0 { format!( ":{}{} ", if HIGHLIGHT { format!(" {}{}", BG_YELLOW, WHITE) } else { "".to_string() }, msg_vec.join(":") ) } else { "".to_string() }, RESET ); } fn success(msg: &str) { let msg = String::from(msg); let mut msg_vec = msg.split(":").collect::>(); println!( "{}{} {} {}{}{}", GREEN, SUCCESS_ICON, ICON_CONNECTOR, msg_vec.remove(0), if msg_vec.len() > 0 { format!( ":{}{} ", if HIGHLIGHT { format!(" {}{}", BG_GREEN, WHITE) } else { "".to_string() }, msg_vec.join(":") ) } else { "".to_string() }, RESET ); } fn info(msg: &str) { let msg = String::from(msg); let mut msg_vec = msg.split(":").collect::>(); println!( "{}{} {} {}{}{}", CYAN, INFO_ICON, ICON_CONNECTOR, msg_vec.remove(0), if msg_vec.len() > 0 { format!( ":{}{} ", if HIGHLIGHT { format!(" {}{}", BG_CYAN, WHITE) } else { "".to_string() }, msg_vec.join(":") ) } else { "".to_string() }, RESET ); } fn error(msg: &str) { let msg = String::from(msg); let mut msg_vec = msg.split(":").collect::>(); eprintln!( "{}{} {} {}{}{}", RED, ERROR_ICON, ICON_CONNECTOR, msg_vec.remove(0), if msg_vec.len() > 0 { format!( ":{}{} ", if HIGHLIGHT { format!(" {}{}", BG_RED, WHITE) } else { "".to_string() }, msg_vec.join(":") ) } else { "".to_string() }, RESET ); }">
// PARAMETERS:

const ICON_CONNECTOR: &str = "->";      // connector between icon and message
const ERROR_ICON: &str = "[ x ]";       // icon for errors
const INFO_ICON: &str = "[ i ]";        // icon for informations
const SUCCESS_ICON: &str = "[ v ]";     // icon for success
const WARNING_ICON: &str = "[ ! ]";     // icon for warnings
const HIGHLIGHT: bool = true;           // should the text after ":" be highlighted

// ---------------

const RED: &str = "\x1b[91m";
const GREEN: &str = "\x1b[92m";
const YELLOW: &str = "\x1b[93m";
const CYAN: &str = "\x1b[96m";
const WHITE: &str = "\x1b[97m";
const RESET: &str = "\x1b[0m";
const BG_RED: &str = "\x1b[41m";
const BG_CYAN: &str = "\x1b[46m";
const BG_GREEN: &str = "\x1b[42m";
const BG_YELLOW: &str = "\x1b[43m";

fn warn(msg: &str) {
    let msg = String::from(msg);

    let mut msg_vec = msg.split(":").collect::<Vec<&str>>();

    println!(
        "{}{} {} {}{}{}",
        YELLOW,
        WARNING_ICON,
        ICON_CONNECTOR,
        msg_vec.remove(0),
        if msg_vec.len() > 0 {
            format!(
                ":{}{} ",
                if HIGHLIGHT {
                    format!(" {}{}", BG_YELLOW, WHITE)
                } else {
                    "".to_string()
                },
                msg_vec.join(":")
            )
        } else {
            "".to_string()
        },
        RESET
    );
}

fn success(msg: &str) {
    let msg = String::from(msg);

    let mut msg_vec = msg.split(":").collect::<Vec<&str>>();

    println!(
        "{}{} {} {}{}{}",
        GREEN,
        SUCCESS_ICON,
        ICON_CONNECTOR,
        msg_vec.remove(0),
        if msg_vec.len() > 0 {
            format!(
                ":{}{} ",
                if HIGHLIGHT {
                    format!(" {}{}", BG_GREEN, WHITE)
                } else {
                    "".to_string()
                },
                msg_vec.join(":")
            )
        } else {
            "".to_string()
        },
        RESET
    );
}

fn info(msg: &str) {
    let msg = String::from(msg);

    let mut msg_vec = msg.split(":").collect::<Vec<&str>>();

    println!(
        "{}{} {} {}{}{}",
        CYAN,
        INFO_ICON,
        ICON_CONNECTOR,
        msg_vec.remove(0),
        if msg_vec.len() > 0 {
            format!(
                ":{}{} ",
                if HIGHLIGHT {
                    format!(" {}{}", BG_CYAN, WHITE)
                } else {
                    "".to_string()
                },
                msg_vec.join(":")
            )
        } else {
            "".to_string()
        },
        RESET
    );
}

fn error(msg: &str) {
    let msg = String::from(msg);

    let mut msg_vec = msg.split(":").collect::<Vec<&str>>();

    eprintln!(
        "{}{} {} {}{}{}",
        RED,
        ERROR_ICON,
        ICON_CONNECTOR,
        msg_vec.remove(0),
        if msg_vec.len() > 0 {
            format!(
                ":{}{} ",
                if HIGHLIGHT {
                    format!(" {}{}", BG_RED, WHITE)
                } else {
                    "".to_string()
                },
                msg_vec.join(":")
            )
        } else {
            "".to_string()
        },
        RESET
    );
}

final

If you have any problem, don't hesitate to open an issue

contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

You might also like...
A pretty, sensible logger for Rust - ideal for running examples and tests on a crate of choice
A pretty, sensible logger for Rust - ideal for running examples and tests on a crate of choice

sensible-env-logger A pretty, sensible logger for Rust - ideal for running examples and tests on a crate of choice. This is a thin wrapper around pret

A rust library for creating and managing logs of arbitrary binary data

A rust library for creating and managing logs of arbitrary binary data. Presently it's used to collect sensor data. But it should generally be helpful in cases where you need to store timeseries data, in a nearly (but not strictly) append-only fashion.

A cool log library built using rust-lang

RustLog A cool log library built using rust-lang Installation: Cargo.toml rustlog = { git = "https://github.com/krishpranav/rustlog" } log = "0.4.17"

Tool to make Solus packaging even easier.

A small tool to make packaging for Solus even easier. Features Remove all packages from the local solbuild repo.

CLI tool that make it easier to perform multiple lighthouse runs towards a single target and output the result in a "plotable" format.

Lighthouse Groupie CLI tool that make it easier to perform multiple lighthouse runs towards a single target and output the result in a "plotable" form

CLI tool that make it easier to perform multiple lighthouse runs towards a single target and output the result in a plotable format.

Lighthouse Aggregator CLI tool that make it easier to perform multiple lighthouse runs towards a single target and output the result in a "plotable" f

Croc-look is a tool to make testing and debuging proc macros easier

croc-look croc-look is a tool to make testing and debuging proc macros easier by these two features Printing the implementation specific generated cod

Set of tools that make it easier for the operator to manage a TAPLE network.
Set of tools that make it easier for the operator to manage a TAPLE network.

⚠️ TAPLE is in early development and should not be used in production ⚠️ TAPLE Tools TAPLE (pronounced T+ 🍎 ['tapΙ™l]) stands for Tracking (Autonomous

Bolt is a desktop application that is designed to make the process of developing and testing APIs easier and more efficient.

Bolt ⚑ Bolt is a desktop application that is designed to make the process of developing and testing APIs easier and more efficient. Quick start πŸ‘©β€πŸ’»

Const equivalents of many [`bytemuck`] functions, and a few additional const functions.

Const equivalents of many bytemuck functions, and a few additional const functions. constmuck uses bytemuck's traits, so any type that implements thos

A rust library that makes reading and writing memory of the Dolphin emulator easier.

dolphin-memory-rs A crate for reading from and writing to the emulated memory of Dolphin in rust. A lot of internals here are directly based on aldela

Rust WebGL2 wrapper with a focus on making high-performance WebAssembly graphics code easier to write and maintain
Rust WebGL2 wrapper with a focus on making high-performance WebAssembly graphics code easier to write and maintain

Limelight Limelight is a WebGL2 wrapper with a focus on making high-performance WebAssembly graphics code easier to write and maintain. demo.mov live

png_defringe_rs is a port of Immorpher's PNG Defringe program written in Rust to achieve easier installation and faster performance.

png_defringe_rs png_defringe_rs is a port of Immorpher's PNG Defringe program written in Rust to achieve easier installation and faster performance. U

A Rust utility library, making easier by taking the hassle out of working. :octocat:
A Rust utility library, making easier by taking the hassle out of working. :octocat:

reddish A Rust utility library, making easier by taking the hassle out of working. Usage Add this to your Cargo.toml: [dependencies] reddish = "0.2.0"

Logging implementation for Rust

log A Rust library providing a lightweight logging facade. log documentation A logging facade provides a single logging API that abstracts over the ac

Structured, contextual, extensible, composable logging for Rust
Structured, contextual, extensible, composable logging for Rust

Getting started Introduction FAQ Crate list slog-rs - The Logging for Rust Introduction (please read) slog is an ecosystem of reusable components for

A highly configurable logging framework for Rust

log4rs log4rs is a highly configurable logging framework modeled after Java's Logback and log4j libraries. Warning If you are using the file rotation

Task-based logging for rust
Task-based logging for rust

task_log task_log is a task-based logger. Installing Just add task_log = 0.1.4 to your Cargo.toml's dependency section. Example Let's get right to the

Minimal DNS server built in Rust with rule system and logging.

MinDNS MinDNS is a minimal DNS server written in Rust. It is intended to be used as a firewall, black-hole or proxy DNS server. ⚑ Features Fully async

Comments
  • [Feature]: Log to file

    [Feature]: Log to file

    Contact Details

    [email protected]

    Feature Description

    I love how simple this is. I need to be able to display which this does, but also write to a log file. I'm currently using pretty-env-logger, but this also is lacking in logging [to a file]. One thing I like about pretty-env-logger is you can set env vars such as RUST_LOG=debug to get debug output.

    Problem Solved

    Writing a log file.

    How can we implement this?

    No response

    enhancement Feedback 
    opened by mabushey 7
Releases(v1.1.0)
Owner
Skwal
Founder of skwal.net, I use arch btw, vive la FranceπŸ‡«πŸ‡·
Skwal
Structured, contextual, extensible, composable logging for Rust

Getting started Introduction FAQ Crate list slog-rs - The Logging for Rust Introduction (please read) slog is an ecosystem of reusable components for

slog-rs 1.4k Jan 3, 2023
A highly configurable logging framework for Rust

log4rs log4rs is a highly configurable logging framework modeled after Java's Logback and log4j libraries. Warning If you are using the file rotation

null 753 Jan 8, 2023
Task-based logging for rust

task_log task_log is a task-based logger. Installing Just add task_log = 0.1.4 to your Cargo.toml's dependency section. Example Let's get right to the

Matt Gleich 2 Feb 28, 2022
A logging library for eBPF programs.

aya-log - a logging library for eBPF programs Overview aya-log is a logging library for eBPF programs written using aya. Think of it as the log crate

null 18 Oct 13, 2022
defmt is a highly efficient logging framework that targets resource-constrained devices, like microcontrollers

defmt defmt ("de format", short for "deferred formatting") is a highly efficient logging framework that targets resource-constrained devices, like mic

Knurling 476 Jan 2, 2023
A pretty, easy-to-use logger for Rust.

pretty-env-logger A simple logger built on top of env_logger. It is configured via an environment variable and writes to standard error with nice colo

Sean McArthur 390 Dec 29, 2022
Application level tracing for Rust.

Website | Chat | Documentation (master branch) Overview tracing is a framework for instrumenting Rust programs to collect structured, event-based diag

Tokio 3.3k Jan 3, 2023
A Rust logger with various features.

Moe Logger (οΌžΟ‰οΌœ) Another logger based on pretty-env-logger and env_logger. Allow writing log to file with features like formatting, file rotation. Usa

Rui Li 4 Sep 24, 2021
godot-logger is an easy-to-use logger for godot-rust projects.

godot-logger is an easy-to-use logger for godot-rust projects. It prints logs to Godot's output console and supports module-specific log levels.

Jan David 10 Nov 17, 2022
Another Key Logger Yet. Rust.

Another Key Logger Yet. Rust. For my very first experience of working with Rust, I decided to manage the keyboard, this time by logging and writing th

(Not) Kearash 0 May 3, 2022