-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[
tryceratops
]: Verbose Log Messages (#3036)
- Loading branch information
Showing
11 changed files
with
315 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
# Errors | ||
def main_function(): | ||
try: | ||
process() | ||
handle() | ||
finish() | ||
except Exception as ex: | ||
logger.exception(f"Found an error: {ex}") # TRY401 | ||
|
||
|
||
def main_function(): | ||
try: | ||
process() | ||
handle() | ||
finish() | ||
except ValueError as bad: | ||
if True is False: | ||
for i in range(10): | ||
logger.exception(f"Found an error: {bad} {good}") # TRY401 | ||
except IndexError as bad: | ||
logger.exception(f"Found an error: {bad} {bad}") # TRY401 | ||
except Exception as bad: | ||
logger.exception(f"Found an error: {bad}") # TRY401 | ||
logger.exception(f"Found an error: {bad}") # TRY401 | ||
|
||
if True: | ||
logger.exception(f"Found an error: {bad}") # TRY401 | ||
|
||
|
||
import logging | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
def func_fstr(): | ||
try: | ||
... | ||
except Exception as ex: | ||
logger.exception(f"Logging an error: {ex}") # TRY401 | ||
|
||
|
||
def func_concat(): | ||
try: | ||
... | ||
except Exception as ex: | ||
logger.exception("Logging an error: " + str(ex)) # TRY401 | ||
|
||
|
||
def func_comma(): | ||
try: | ||
... | ||
except Exception as ex: | ||
logger.exception("Logging an error:", ex) # TRY401 | ||
|
||
|
||
# OK | ||
def main_function(): | ||
try: | ||
process() | ||
handle() | ||
finish() | ||
except Exception as ex: | ||
logger.exception(f"Found an error: {er}") | ||
logger.exception(f"Found an error: {ex.field}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
use crate::ast::helpers::is_logger_candidate; | ||
use crate::ast::visitor; | ||
use crate::ast::visitor::Visitor; | ||
use rustpython_parser::ast::{Expr, ExprKind}; | ||
|
||
#[derive(Default)] | ||
/// Collect `logging`-like calls from an AST. | ||
pub struct LoggerCandidateVisitor<'a> { | ||
pub calls: Vec<(&'a Expr, &'a Expr)>, | ||
} | ||
|
||
impl<'a, 'b> Visitor<'b> for LoggerCandidateVisitor<'a> | ||
where | ||
'b: 'a, | ||
{ | ||
fn visit_expr(&mut self, expr: &'b Expr) { | ||
if let ExprKind::Call { func, .. } = &expr.node { | ||
if is_logger_candidate(func) { | ||
self.calls.push((expr, func)); | ||
} | ||
} | ||
visitor::walk_expr(self, expr); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
110 changes: 110 additions & 0 deletions
110
crates/ruff/src/rules/tryceratops/rules/verbose_log_message.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
use rustpython_parser::ast::{Excepthandler, ExcepthandlerKind, Expr, ExprContext, ExprKind}; | ||
|
||
use ruff_macros::{define_violation, derive_message_formats}; | ||
|
||
use crate::ast::types::Range; | ||
use crate::ast::visitor; | ||
use crate::ast::visitor::Visitor; | ||
use crate::checkers::ast::Checker; | ||
use crate::registry::Diagnostic; | ||
use crate::rules::tryceratops::helpers::LoggerCandidateVisitor; | ||
use crate::violation::Violation; | ||
|
||
define_violation!( | ||
/// ### What it does | ||
/// Checks for excessive logging of exception objects. | ||
/// | ||
/// ### Why is this bad? | ||
/// When logging exceptions via `logging.exception`, the exception object | ||
/// is logged automatically. Including the exception object in the log | ||
/// message is redundant and can lead to excessive logging. | ||
/// | ||
/// ### Example | ||
/// ```python | ||
/// try: | ||
/// ... | ||
/// except ValueError as e: | ||
/// logger.exception(f"Found an error: {e}") | ||
/// ``` | ||
/// | ||
/// Use instead: | ||
/// ```python | ||
/// try: | ||
/// ... | ||
/// except ValueError as e: | ||
/// logger.exception(f"Found an error") | ||
/// ``` | ||
pub struct VerboseLogMessage; | ||
); | ||
impl Violation for VerboseLogMessage { | ||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
format!("Redundant exception object included in `logging.exception` call") | ||
} | ||
} | ||
|
||
#[derive(Default)] | ||
struct NameVisitor<'a> { | ||
names: Vec<(&'a str, &'a Expr)>, | ||
} | ||
|
||
impl<'a, 'b> Visitor<'b> for NameVisitor<'a> | ||
where | ||
'b: 'a, | ||
{ | ||
fn visit_expr(&mut self, expr: &'b Expr) { | ||
match &expr.node { | ||
ExprKind::Name { | ||
id, | ||
ctx: ExprContext::Load, | ||
} => self.names.push((id, expr)), | ||
ExprKind::Attribute { .. } => {} | ||
_ => visitor::walk_expr(self, expr), | ||
} | ||
} | ||
} | ||
|
||
/// TRY401 | ||
pub fn verbose_log_message(checker: &mut Checker, handlers: &[Excepthandler]) { | ||
for handler in handlers { | ||
let ExcepthandlerKind::ExceptHandler { name, body, .. } = &handler.node; | ||
let Some(target) = name else { | ||
continue; | ||
}; | ||
|
||
// Find all calls to `logging.exception`. | ||
let calls = { | ||
let mut visitor = LoggerCandidateVisitor::default(); | ||
visitor.visit_body(body); | ||
visitor.calls | ||
}; | ||
|
||
for (expr, func) in calls { | ||
let ExprKind::Call { args, .. } = &expr.node else { | ||
continue; | ||
}; | ||
if let ExprKind::Attribute { attr, .. } = &func.node { | ||
if attr == "exception" { | ||
// Collect all referenced names in the `logging.exception` call. | ||
let names: Vec<(&str, &Expr)> = { | ||
let mut names = Vec::new(); | ||
for arg in args { | ||
let mut visitor = NameVisitor::default(); | ||
visitor.visit_expr(arg); | ||
names.extend(visitor.names); | ||
} | ||
names | ||
}; | ||
for (id, expr) in names { | ||
if id == target { | ||
checker.diagnostics.push(Diagnostic::new( | ||
VerboseLogMessage, | ||
Range::from_located(expr), | ||
)); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.