-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathconditional_formatting.rs
More file actions
209 lines (184 loc) · 6.8 KB
/
Copy pathconditional_formatting.rs
File metadata and controls
209 lines (184 loc) · 6.8 KB
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
//! Conditional formatting based on runtime context
//!
//! Use conditional formatting to adapt error output based on runtime
//! conditions:
//! - Hide sensitive data based on environment (production vs development)
//! - Show/hide verbose info based on feature flags or debug settings
//! - Customize visibility based on user permissions or logging levels
//!
//! Pattern: Check runtime state in AttachmentFormatterHook to control
//! placement/visibility
use std::env;
use rootcause::{
hooks::{Hooks, attachment_formatter::AttachmentFormatterHook},
prelude::*,
report_attachment::ReportAttachmentRef,
};
// Example 1: Hide sensitive data in production
/// API credentials that should never be exposed in production logs
#[derive(Debug)]
struct ApiCredentials {
api_key: String,
secret: String,
}
impl core::fmt::Display for ApiCredentials {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
// Show partial data in development for debugging
write!(
f,
"API Key: {}..., Secret: {}...",
&self.api_key[..8],
&self.secret[..8]
)
}
}
/// Formatter that conditionally hides credentials based on environment
/// The same pattern works for feature flags, user permissions, etc.
struct CredentialsFormatter;
impl AttachmentFormatterHook<ApiCredentials> for CredentialsFormatter {
fn preferred_formatting_style(
&self,
_attachment: ReportAttachmentRef<'_, ApiCredentials>,
report_formatting_function: rootcause::handlers::FormattingFunction,
) -> rootcause::handlers::AttachmentFormattingStyle {
use rootcause::handlers::{
AttachmentFormattingPlacement, AttachmentFormattingStyle, FormattingFunction,
};
if is_production() {
// Hide when condition is true (production, feature disabled, insufficient
// permissions, etc.)
AttachmentFormattingStyle {
placement: AttachmentFormattingPlacement::Hidden,
// force Display formatting, just in case something slips thorugh
function: FormattingFunction::Display,
priority: 0,
}
} else {
// Show when condition is false
AttachmentFormattingStyle {
placement: AttachmentFormattingPlacement::Inline,
function: report_formatting_function,
priority: 0,
}
}
}
}
// Example 2: Show verbose debug info only in development
/// Detailed debugging information that's too verbose for production
#[derive(Debug)]
struct DebugSnapshot {
memory_mb: usize,
thread_count: usize,
active_connections: usize,
last_gc_ms: u64,
}
impl core::fmt::Display for DebugSnapshot {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
writeln!(f, "Debug Snapshot:")?;
writeln!(f, " Memory: {} MB", self.memory_mb)?;
writeln!(f, " Threads: {}", self.thread_count)?;
writeln!(f, " Connections: {}", self.active_connections)?;
write!(f, " Last GC: {} ms", self.last_gc_ms)
}
}
/// Formatter that conditionally hides verbose info based on environment
/// Could also check debug flags, log levels, feature toggles, etc.
struct DebugSnapshotFormatter;
impl AttachmentFormatterHook<DebugSnapshot> for DebugSnapshotFormatter {
fn preferred_formatting_style(
&self,
_attachment: ReportAttachmentRef<'_, DebugSnapshot>,
report_formatting_function: rootcause::handlers::FormattingFunction,
) -> rootcause::handlers::AttachmentFormattingStyle {
use rootcause::handlers::{
AttachmentFormattingPlacement, AttachmentFormattingStyle, FormattingFunction,
};
if is_production() {
// Hide when runtime condition is true
AttachmentFormattingStyle {
placement: AttachmentFormattingPlacement::Hidden,
function: FormattingFunction::Display,
priority: 0,
}
} else {
// Show in appendix when runtime condition is false
AttachmentFormattingStyle {
placement: AttachmentFormattingPlacement::Appendix {
appendix_name: "Debug Info",
},
function: report_formatting_function,
priority: 0,
}
}
}
}
fn is_production() -> bool {
env::var("APP_ENV")
.map(|v| v == "production")
.unwrap_or(false)
}
fn get_environment_name() -> String {
env::var("APP_ENV").unwrap_or_else(|_| "development".to_string())
}
fn authenticate_api() -> Result<(), Report> {
let creds = ApiCredentials {
api_key: "sk_live_1234567890abcdef".to_string(),
secret: "secret_1234567890abcdef".to_string(),
};
Err(report!(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"API authentication failed",
))
.attach(creds)
.into_dynamic())
}
fn process_request() -> Result<(), Report> {
let snapshot = DebugSnapshot {
memory_mb: 256,
thread_count: 8,
active_connections: 42,
last_gc_ms: 15,
};
Err(report!("Request processing failed")
.attach("Processing step: validation")
.attach(snapshot)
.into_dynamic())
}
fn main() {
println!("=== Conditional Formatting Example ===\n");
let env = get_environment_name();
println!("Running in: {} mode", env);
println!("(Set APP_ENV=production to see different behavior)\n");
// Install conditional formatting hooks
Hooks::new()
.attachment_formatter::<ApiCredentials, _>(CredentialsFormatter)
.attachment_formatter::<DebugSnapshot, _>(DebugSnapshotFormatter)
.install()
.expect("failed to install hooks");
println!("Example 1: Conditionally hide sensitive data\n");
match authenticate_api() {
Ok(()) => println!("Success"),
Err(error) => {
eprintln!("{error}\n");
if is_production() {
println!("Notice: Credentials were hidden based on environment check");
println!("(Same pattern works for feature flags, permissions, etc.)\n");
} else {
println!("Notice: Credentials shown - condition evaluated to false\n");
}
}
}
println!("Example 2: Conditionally hide verbose info\n");
match process_request() {
Ok(()) => println!("Success"),
Err(error) => {
eprintln!("{error}\n");
if is_production() {
println!("Notice: Debug info hidden based on runtime check");
println!("(Could also check debug flags, log levels, etc.)");
} else {
println!("Notice: Debug info shown - use appendix to avoid clutter");
}
}
}
}