hyperion_framework/logging/logging_service.rs
1// -------------------------------------------------------------------------------------------------
2// Hyperion Framework
3// https://github.com/robert-hannah/hyperion-framework
4//
5// A lightweight component-based TCP framework for building service-oriented Rust applications with
6// CLI control, async messaging, and lifecycle management.
7//
8// Copyright 2025 Robert Hannah
9//
10// Licensed under the Apache License, Version 2.0 (the "License");
11// you may not use this file except in compliance with the License.
12// You may obtain a copy of the License at
13//
14// http://www.apache.org/licenses/LICENSE-2.0
15//
16// Unless required by applicable law or agreed to in writing, software
17// distributed under the License is distributed on an "AS IS" BASIS,
18// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19// See the License for the specific language governing permissions and
20// limitations under the License.
21// -------------------------------------------------------------------------------------------------
22
23// Package
24use colored::*;
25use log::{Level, LevelFilter, Metadata, Record, SetLoggerError};
26
27// Define a simple logger that will handle logging messages with colours
28pub struct LoggingService {
29 pub min_log_level: LevelFilter,
30}
31
32impl log::Log for LoggingService {
33 fn enabled(&self, metadata: &Metadata) -> bool {
34 metadata.level().to_level_filter() <= self.min_log_level
35 }
36
37 fn log(&self, record: &Record) {
38 if self.enabled(record.metadata()) {
39 let level = match record.level() {
40 Level::Error => "ERROR".red(),
41 Level::Warn => "WARN".yellow(),
42 Level::Info => "INFO".green(),
43 Level::Debug => "DEBUG".bright_cyan(),
44 Level::Trace => "TRACE".blue(),
45 };
46
47 // Create the log message
48 let log_message = format!("{} - {}", level, record.args());
49 println!("{log_message}");
50 }
51 }
52
53 fn flush(&self) {}
54}
55
56// Function to initialise the logger - not part of the struct
57pub fn initialise_logger(log_level: LevelFilter) -> Result<(), SetLoggerError> {
58 let logger = LoggingService {
59 min_log_level: log_level,
60 };
61
62 // Set the logger as the global logger
63 log::set_max_level(logger.min_log_level);
64 log::set_boxed_logger(Box::new(logger))?;
65 Ok(())
66}