Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Last active May 7, 2023 23:57
Show Gist options
  • Save dpaluy/c11802820ed20f1412daf7507d2d58a4 to your computer and use it in GitHub Desktop.
Save dpaluy/c11802820ed20f1412daf7507d2d58a4 to your computer and use it in GitHub Desktop.
Hierarchical logger
# 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
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
@dpaluy
Copy link
Author

dpaluy commented May 7, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment