Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #52 from Lykos/master

Example for lazy evaluation
  • Loading branch information...
commit 49248189af10e0eae77b51a1b0bb9507732b3a3a 2 parents 47be512 + 94a0601
@TwP authored
Showing with 42 additions and 0 deletions.
  1. +1 −0  README.rdoc
  2. +41 −0 examples/lazy.rb
View
1  README.rdoc
@@ -83,6 +83,7 @@ package. The recommended reading order is the following:
* {classes.rb}[https://github.com/TwP/logging/blob/master/examples/classes.rb]
* {hierarchies.rb}[https://github.com/TwP/logging/blob/master/examples/hierarchies.rb]
* {names.rb}[https://github.com/TwP/logging/blob/master/examples/names.rb]
+* {lazy.rb}[https://github.com/TwP/logging/blob/master/examples/lazy.rb]
* {appenders.rb}[https://github.com/TwP/logging/blob/master/examples/appenders.rb]
* {layouts.rb}[https://github.com/TwP/logging/blob/master/examples/layouts.rb]
* {formatting.rb}[https://github.com/TwP/logging/blob/master/examples/formatting.rb]
View
41 examples/lazy.rb
@@ -0,0 +1,41 @@
+# :stopdoc:
+#
+# It happens sometimes that it is very expensive to construct a logging
+# message, e.g. if a big object structure has to be traversed in an
+# object.to_s method. But if the message is logged with a level that
+# doesn't actually get displayed, it would be a waste of time to
+# construct it. The logging framework provides a way to
+# address this in an elegant way using lazy evaluation.
+#
+
+ require 'logging'
+
+ Logging.logger.root.appenders = Logging.appenders.stdout
+ Logging.logger.root.level = :info
+
+ # We use this dummy method in order to see if the method gets called, but in practice,
+ # this method might do complicated string operations to construct a log message.
+ def expensive_method
+ puts "Called!"
+ "Expensive message"
+ end
+
+ log = Logging.logger['Lazy']
+
+ # If you log this message the usual way, expensive_method gets called before
+ # debug, hence the Logging framework has no chance to stop it from being executed
+ # immediately.
+ log.info("Normal")
+ log.debug(expensive_method)
+
+ # If we put the message into a block, then the block is not executed, if
+ # the message is not needed with the current log level.
+ log.info("Block unused")
+ log.debug { expensive_method }
+
+ # If the log message is needed with the current log level, then the block is of
+ # course executed and the log message appears as expected.
+ log.info("Block used")
+ log.warn { expensive_method }
+
+# :startdoc:
Please sign in to comment.
Something went wrong with that request. Please try again.