Skip to content

Latest commit

 

History

History
50 lines (40 loc) · 1.56 KB

filter-log.zh.md

File metadata and controls

50 lines (40 loc) · 1.56 KB

通过匹配多个正则表达式,筛选日志文件

[![regex-badge]][regex] [![cat-text-processing-badge]][cat-text-processing]

读取名为application.log的文件,并且只输出包含“version x.x.x”、或一些 IP 地址跟着端口 443(例如“192.168.0.1:443”)或特殊 warning 的那些行。

一个regex::RegexSetBuilder组成一个regex::RegexSet。 因为反斜杠在正则表达式中,非常常见,所以使用原始字符串文本能让它们更具可读性。

# #[macro_use]
# extern crate error_chain;
extern crate regex;

use std::fs::File;
use std::io::{BufReader, BufRead};
use regex::RegexSetBuilder;

# error_chain! {
#     foreign_links {
#         Io(std::io::Error);
#         Regex(regex::Error);
#     }
# }
#
fn run() -> Result<()> {
    let log_path = "application.log";
    let buffered = BufReader::new(File::open(log_path)?);

    let set = RegexSetBuilder::new(&[
        r#"version "\d\.\d\.\d""#,
        r#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:443"#,
        r#"warning.*timeout expired"#,
    ]).case_insensitive(true)
        .build()?;

    buffered
        .lines()
        .filter_map(|line| line.ok())
        .filter(|line| set.is_match(line.as_str()))
        .for_each(|x| println!("{}", x));

    Ok(())
}
#
# quick_main!(run);