Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should logging code throw an Exception?

Tags:

c#

exception

I'm designing a small library which should help logging into different destinations (files, databases, etc.). However, I'm not sure if I should throw exceptions if something goes wrong (e.g. a file cannot be written to)?

If I throw exceptions (related to logging), the developer of applications using my library can clearly see that logging does not happen as intended. On the other hand, it can be an additional source of problems.

If I suppress exceptions and just quietly not log, the developer may miss important information if e.g. the database cannot be reached.

Are there any suggestions, general guidelines (if a then b, etc.) on how to approach this?


As I have read so far:

Microsofts Guidelines for Exceptions state:

✗ DO NOT have public members that can either throw or not based on some option.

So an option whether or not to throw an exception would be against these guidelines, but they do not give statements on throwing exceptions if it is uncertain how likely an exception is.

I also read in this question/answer that I should not catch exceptions because I cannot do anything meaningful with them, but the question was targeting an Enterprise-level system, while my question asks on a more general level.

like image 784
MechMK1 Avatar asked Mar 17 '23 02:03

MechMK1


1 Answers

Do not dogmatically follow any guidelines. Consult the guidelines, and then do what you think is best for solving the problem at hand.

A logger is a special piece of software: it has special needs and considerations. Therefore, the guidelines issued by microsoft do not apply to your logger in exactly the same way as they apply to general purpose software.

In my book, it is perfectly fine to vary your logger's behavior based on an "Is-This-A-Development-Environment" flag, and to throw exceptions if true, or suppress these exceptions (possibly logging them in some less-error-prone medium) otherwise.

like image 95
Mike Nakis Avatar answered Mar 29 '23 06:03

Mike Nakis