Re: [jruby-user] Log4j2 and JRuby classes

"R. Tyler Croy" <[email protected]> Sat, 15 Nov 2014 07:11:27 -0800
Newsgroups gmane.comp.lang.jruby.user
Message-ID <20141115151126.GP4392@kiwi>
(replies inline)

On Sat, 15 Nov 2014, Greg Allen wrote:

> I am trying to use log4j2 on my Ruby classes but can't figure out how to 
> get the logger instance for a ruby class.  Here's some sample code:
> 
> java_import org.apache.logging.log4j.LogManager
> class TestClass
>      @log = LogManager.getLogger(TestClass)
> 
>      def logme
>          @log.info('Test the logging')
>      end
> end


There are two things that are happening here, because of there the
`logManager.getLogger` line is occurring, it's creating the `@log` instance
variable on the *class* object. Whereas the `logme` method is an instance
method which is attempting to access the instance variable on the initialized
TestClass object.

If you change this to:

  class TestClass
    def initialize
      @log = LogManager.getLogger(TestClass)
    end
 
    def logme
      @log.info('Test the logging')
    end
  end

Then you will access the right `@log` in the right scope


- R. Tyler Croy

------------------------------------------------------
     Code: <https://github.com/rtyler>
  Chatter: <https://twitter.com/agentdero>

  % gpg --keyserver keys.gnupg.net --recv-key 3F51E16F
------------------------------------------------------
signature.asc (application/pgp-signature, 181 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1

iEYEARECAAYFAlRnbR4ACgkQFCbH3D9R4W8yDwCgsYQjl3X8ezM1ks2VRDRxPuip
3NwAoIlkbfPNlfF0fc3WkV3jPMj9621j
=jMb0
-----END PGP SIGNATURE-----