dm_database_sqllog2db/
error_logger.rs1use crate::error::{Error, ExportError, Result};
3use log::{debug, info};
4use std::collections::HashMap;
5use std::fs::{File, OpenOptions};
6use std::io::{BufWriter, Write};
7use std::path::{Path, PathBuf};
8
9#[derive(Debug)]
11pub struct ParseErrorRecord {
12 pub file_path: String,
14 pub error_message: String,
16 pub raw_content: Option<String>,
18 pub line_number: Option<usize>,
20}
21
22#[derive(Debug, Default)]
24pub struct ErrorMetrics {
25 pub total: usize,
27 pub by_category: HashMap<String, usize>,
29 pub parse_variants: HashMap<String, usize>,
31}
32
33impl ErrorMetrics {
34 fn incr_category(&mut self, cat: &str) {
35 *self.by_category.entry(cat.to_string()).or_insert(0) += 1;
36 self.total += 1;
37 }
38
39 fn incr_parse_variant(&mut self, variant: &str) {
40 *self.parse_variants.entry(variant.to_string()).or_insert(0) += 1;
41 }
42}
43
44pub struct ErrorLogger {
45 writer: BufWriter<File>,
46 path: String,
47 count: usize,
48 metrics: ErrorMetrics,
49}
50
51impl ErrorLogger {
52 pub fn new<P: AsRef<Path>>(path: P) -> Result<Self> {
54 let path_ref = path.as_ref();
55 let path_str = path_ref.to_string_lossy().to_string();
56
57 if let Some(parent) = path_ref.parent().filter(|p| !p.exists()) {
59 std::fs::create_dir_all(parent).map_err(|e| {
60 Error::Export(ExportError::FileCreateFailed {
61 path: parent.to_path_buf(),
62 reason: e.to_string(),
63 })
64 })?;
65 }
66
67 let file = OpenOptions::new()
69 .create(true)
70 .append(true)
71 .open(path_ref)
72 .map_err(|e| {
73 Error::Export(ExportError::FileCreateFailed {
74 path: path_ref.to_path_buf(),
75 reason: e.to_string(),
76 })
77 })?;
78
79 info!("Error logger initialized: {}", path_str);
80
81 Ok(Self {
82 writer: BufWriter::new(file),
83 path: path_str,
84 count: 0,
85 metrics: ErrorMetrics::default(),
86 })
87 }
88
89 pub fn log_error(&mut self, record: ParseErrorRecord) -> Result<()> {
91 let raw = record.raw_content.clone().unwrap_or_default();
93 let line_no = record
94 .line_number
95 .map(|n| n.to_string())
96 .unwrap_or_default();
97 let line = format!(
98 "{} | {} | {} | {}",
99 record.file_path,
100 record.error_message,
101 raw.replace('\n', "\\n"),
102 line_no
103 );
104
105 writeln!(self.writer, "{}", line).map_err(|e| {
106 Error::Export(ExportError::FileWriteFailed {
107 path: PathBuf::from(&self.path),
108 reason: e.to_string(),
109 })
110 })?;
111
112 self.count += 1;
113 self.metrics.incr_category("parse");
115 Ok(())
116 }
117
118 pub fn log_parse_error(
120 &mut self,
121 file_path: &str,
122 error: &dm_database_parser_sqllog::ParseError,
123 ) -> Result<()> {
124 let record = ParseErrorRecord {
125 file_path: file_path.to_string(),
126 error_message: format!("{:?}", error),
127 raw_content: None, line_number: None,
129 };
130 let variant = format!("{:?}", error);
132 self.metrics.incr_parse_variant(&variant);
133 self.log_error(record)
134 }
135
136 pub fn flush(&mut self) -> Result<()> {
139 self.writer.flush().map_err(|e| {
140 Error::Export(ExportError::FileWriteFailed {
141 path: PathBuf::from(&self.path),
142 reason: format!("Flush failed: {}", e),
143 })
144 })?;
145 Ok(())
146 }
147
148 pub fn finalize(&mut self) -> Result<()> {
150 self.flush()?;
151
152 if self.count > 0 {
153 info!(
154 "Error log written: {} ({} records, categories: {:?})",
155 self.path, self.count, self.metrics.by_category
156 );
157 } else {
158 debug!("No error records to write");
159 }
160 Ok(())
161 }
162}