Open
Description
Description:
When working with logger.catch()
, users often want to log a success message and perform additional actions when operations complete without exceptions. This enhancement would streamline error handling and success reporting.
Updated Proposed Signature:
def catch(
self,
exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = Exception,
*,
level: Union[str, int] = "ERROR",
reraise: bool = False,
onerror: Optional[Callable[[BaseException], None]] = None,
exclude: Optional[Union[Type[BaseException], Tuple[Type[BaseException], ...]]] = None,
default: Any = None,
message: str = "An error has been caught in function '{record[function]}', "
"process '{record[process].name}' ({record[process].id}), "
"thread '{record[thread].name}' ({record[thread].id}):",
# New parameters:
success_message: Optional[str] = None,
success_level: Union[str, int] = "SUCCESS",
on_success: Optional[Callable[[], None]] = None
) -> "Catcher":
Implementation Notes:
- Added
success_message
parameter - when None (default), no success message is logged - Added
success_level
parameter with "SUCCESS" as the default level - Added
on_success
callback parameter for more complex success handling - Maintained all existing parameters with their original defaults
Note: I've included type hints to clarify, make the proposal more complete, and avoid repeating myself.
Example Usage:
# With success message only
@logger.catch(success_message="Database connection established successfully")
def connect_to_database():
# risky connection code here
return connection
# With both success message and callback
@logger.catch(
success_message="Operation '{record[function]}' completed",
on_success=lambda: notify_admin("Operation completed")
)
def some_operation():
...
# As a context manager
with logger.catch(
success_message="File processed successfully",
on_success=lambda: update_status_dashboard()
):
process_file(filename)
Implementation Considerations:
- For context managers, the success message and callback would be triggered when exiting the context without an exception
- For decorators, they would be triggered before returning the result
- The success message would support the same formatting capabilities as other logger messages
- The callback function could potentially receive the function's return value as a parameter
I'm ready to contribute to implementing this feature if the maintainers are interested in the enhancement.