Last active
May 7, 2023 23:57
-
-
Save dpaluy/c11802820ed20f1412daf7507d2d58a4 to your computer and use it in GitHub Desktop.
Hierarchical logger
This file contains hidden or 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
# Let's see the logger in practice. Imagine, we want to | |
# perform some actions on each project assigned to a | |
# specific user (whose ID is in params[:id]). | |
logger. log ("Find user") do | |
user = User.find (params [:id]) | |
logger.log("Found #{user.email]") | |
logger.log("Iterate over projects") do | |
user.projects.find_each do |project| | |
logger.log(project.name) do | |
# Do something with the project. | |
end | |
end | |
end | |
end | |
# The code above would produce logs like: | |
# | |
# Find user | |
# Found [email protected] | |
# Iterating over projects | |
# Acme | |
# Manhattan |
This file contains hidden or 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
class HierarchicalLogger | |
# io is an I0 object where logs will be printed. | |
def initialize(io) | |
@io = io | |
# Level starts at 0, i.e. no indentation. | |
@level = 0 | |
end | |
def log(message) | |
# First, log the message while taking the | |
# current indentation level into account. | |
@io.puts(" " * (level + message. to_s) | |
# If no block is given then we're done. | |
return if !block_given? | |
# Otherwise, increase the indentation level | |
@level += 1 | |
# ... run the block | |
result = yield | |
# ... and go back to the previous level. | |
@level -= 1 | |
result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
source: https://twitter.com/gregnavis/status/1630191075070713858