rlg/log_format.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
// log_format.rs
// Copyright © 2024 RustLogs (RLG). All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::error::{RlgError, RlgResult};
use crate::utils::sanitize_log_message;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
/// Compiled regular expressions for log format validation.
static CLF_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r#"^(?P<host>\S+) (?P<ident>\S+) (?P<user>\S+) \[(?P<time>[^\]]+)\] "(?P<method>\S+) (?P<path>\S+) (?P<protocol>\S+)" (?P<status>\d{3}) (?P<size>\d+|-)$"#
).unwrap()
});
static CEF_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r#"^CEF:\d+\|[^|]+\|[^|]+\|[^|]+\|[^|]+\|[^|]+\|[^|]+\|.*$"#,
)
.unwrap()
});
static W3C_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r#"^#Fields:.*
.+$"#,
)
.unwrap()
});
/// An enumeration of the different log formats that can be used.
///
/// # Variants
/// * `CLF` - Common Log Format.
/// * `JSON` - JavaScript Object Notation.
/// * `CEF` - Common Event Format.
/// * `ELF` - Extended Log Format.
/// * `W3C` - W3C Extended Log File Format.
/// * `GELF` - Graylog Extended Log Format.
/// * `ApacheAccessLog` - Apache HTTP server access logs.
/// * `Logstash` - Logstash JSON format.
/// * `Log4jXML` - Log4j's XML format.
/// * `NDJSON` - Newline Delimited JSON.
///
/// # Examples
/// ```
/// use rlg::log_format::LogFormat;
/// let format: LogFormat = "CLF".parse().unwrap();
/// assert_eq!(format, LogFormat::CLF);
/// ```
#[non_exhaustive]
#[derive(
Clone,
Copy,
Debug,
Deserialize,
Eq,
Hash,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
pub enum LogFormat {
/// Common Log Format.
CLF,
/// JavaScript Object Notation.
JSON,
/// Common Event Format.
CEF,
/// Extended Log Format.
ELF,
/// W3C Extended Log File Format.
W3C,
/// Graylog Extended Log Format.
GELF,
/// Apache HTTP server access logs.
ApacheAccessLog,
/// Logstash JSON format.
Logstash,
/// Log4j's XML format.
Log4jXML,
/// Newline Delimited JSON.
NDJSON,
}
impl FromStr for LogFormat {
type Err = RlgError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"clf" => Ok(LogFormat::CLF),
"json" => Ok(LogFormat::JSON),
"cef" => Ok(LogFormat::CEF),
"elf" => Ok(LogFormat::ELF),
"w3c" => Ok(LogFormat::W3C),
"gelf" => Ok(LogFormat::GELF),
"apacheaccesslog" => Ok(LogFormat::ApacheAccessLog),
"logstash" => Ok(LogFormat::Logstash),
"log4jxml" => Ok(LogFormat::Log4jXML),
"ndjson" => Ok(LogFormat::NDJSON),
_ => Err(RlgError::FormatParseError(format!(
"Unknown log format: {}",
s
))),
}
}
}
impl LogFormat {
/// Validates if a given string adheres to a particular log format.
///
/// # Arguments
///
/// * `input` - A string slice that holds the log entry to be validated.
///
/// # Returns
///
/// * `bool` - Returns `true` if the input matches the log format, `false` otherwise.
///
/// # Example
///
/// ```
/// use rlg::log_format::LogFormat;
/// let is_valid = LogFormat::CLF.validate("127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326");
/// assert!(is_valid);
/// ```
pub fn validate(&self, input: &str) -> bool {
match self {
LogFormat::CLF | LogFormat::ApacheAccessLog => {
CLF_REGEX.is_match(input)
}
LogFormat::JSON
| LogFormat::Logstash
| LogFormat::NDJSON => {
serde_json::from_str::<serde_json::Value>(input).is_ok()
}
LogFormat::CEF => CEF_REGEX.is_match(input),
LogFormat::ELF | LogFormat::W3C => {
W3C_REGEX.is_match(input)
}
LogFormat::GELF => {
serde_json::from_str::<serde_json::Value>(input).is_ok()
}
LogFormat::Log4jXML => {
input.trim_start().starts_with("<log4j:event")
}
}
}
/// Formats a log entry according to the specified log format.
///
/// # Arguments
///
/// * `entry` - A string slice that holds the log entry to be formatted.
///
/// # Returns
///
/// A `RlgResult<String>` containing the formatted log entry or an error if the formatting fails.
///
/// # Example
///
/// ```
/// use rlg::log_format::LogFormat;
/// let formatted_log = LogFormat::CLF.format_log("127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326").unwrap();
/// ```
pub fn format_log(&self, entry: &str) -> RlgResult<String> {
let sanitized_entry = sanitize_log_message(entry);
match self {
LogFormat::CLF
| LogFormat::ApacheAccessLog
| LogFormat::CEF
| LogFormat::ELF
| LogFormat::W3C
| LogFormat::Log4jXML => Ok(sanitized_entry),
LogFormat::JSON
| LogFormat::Logstash
| LogFormat::NDJSON
| LogFormat::GELF => serde_json::to_string_pretty(
&serde_json::from_str::<serde_json::Value>(
&sanitized_entry,
)
.map_err(|e| {
RlgError::FormattingError(format!(
"Invalid JSON: {}",
e
))
})?,
)
.map_err(|e| {
RlgError::FormattingError(format!(
"JSON formatting error: {}",
e
))
}),
}
}
}
impl fmt::Display for LogFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
LogFormat::CLF => "CLF",
LogFormat::JSON => "JSON",
LogFormat::CEF => "CEF",
LogFormat::ELF => "ELF",
LogFormat::W3C => "W3C",
LogFormat::GELF => "GELF",
LogFormat::ApacheAccessLog => "Apache Access Log",
LogFormat::Logstash => "Logstash",
LogFormat::Log4jXML => "Log4j XML",
LogFormat::NDJSON => "NDJSON",
};
write!(f, "{}", s)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_log_format_from_str() {
assert_eq!(LogFormat::from_str("clf").unwrap(), LogFormat::CLF);
assert_eq!(
LogFormat::from_str("JSON").unwrap(),
LogFormat::JSON
);
assert!(LogFormat::from_str("invalid").is_err());
}
#[test]
fn test_log_format_validate() {
let clf_log = r#"127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326"#;
assert!(LogFormat::CLF.validate(clf_log));
let json_log = r#"{"level":"info","message":"Test log","timestamp":"2023-05-17T12:34:56Z"}"#;
assert!(LogFormat::JSON.validate(json_log));
}
#[test]
fn test_log_format_format_log() {
let json_log = r#"{"level":"info","message":"Test log","timestamp":"2023-05-17T12:34:56Z"}"#;
let formatted = LogFormat::JSON.format_log(json_log).unwrap();
assert!(formatted.contains("{\n")); // Check if it's pretty-printed
let clf_log = r#"127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326"#;
let formatted = LogFormat::CLF.format_log(clf_log).unwrap();
assert_eq!(formatted, clf_log); // CLF should remain unchanged
}
}