Magento 2: Replacement for Mage::log method?












86















In Magento 1, if you wanted to send a message to the logs, you'd use a static method on the global Mage class.



Mage::log($message, Zend_Log::DEBUG, "my-log-file.log");


Is there an equivalent in Magento 2? I've googled through the dev docs site and haven't seen anything obvious that pops out. There's this Inchoo article, but it's from almost a year ago and so much has changed since then.



As a Magento 2 module developer, if I want to replace code like the following in Magento 1



Mage::log($message, Zend_Log::DEBUG, "my-log-file.log");


What's the bare minimum I need to do?










share|improve this question





























    86















    In Magento 1, if you wanted to send a message to the logs, you'd use a static method on the global Mage class.



    Mage::log($message, Zend_Log::DEBUG, "my-log-file.log");


    Is there an equivalent in Magento 2? I've googled through the dev docs site and haven't seen anything obvious that pops out. There's this Inchoo article, but it's from almost a year ago and so much has changed since then.



    As a Magento 2 module developer, if I want to replace code like the following in Magento 1



    Mage::log($message, Zend_Log::DEBUG, "my-log-file.log");


    What's the bare minimum I need to do?










    share|improve this question



























      86












      86








      86


      32






      In Magento 1, if you wanted to send a message to the logs, you'd use a static method on the global Mage class.



      Mage::log($message, Zend_Log::DEBUG, "my-log-file.log");


      Is there an equivalent in Magento 2? I've googled through the dev docs site and haven't seen anything obvious that pops out. There's this Inchoo article, but it's from almost a year ago and so much has changed since then.



      As a Magento 2 module developer, if I want to replace code like the following in Magento 1



      Mage::log($message, Zend_Log::DEBUG, "my-log-file.log");


      What's the bare minimum I need to do?










      share|improve this question
















      In Magento 1, if you wanted to send a message to the logs, you'd use a static method on the global Mage class.



      Mage::log($message, Zend_Log::DEBUG, "my-log-file.log");


      Is there an equivalent in Magento 2? I've googled through the dev docs site and haven't seen anything obvious that pops out. There's this Inchoo article, but it's from almost a year ago and so much has changed since then.



      As a Magento 2 module developer, if I want to replace code like the following in Magento 1



      Mage::log($message, Zend_Log::DEBUG, "my-log-file.log");


      What's the bare minimum I need to do?







      magento2 log psr-logger






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 11 '17 at 21:35









      Rafael Corrêa Gomes

      4,28222962




      4,28222962










      asked Dec 3 '15 at 4:06









      Alan StormAlan Storm

      28.6k18114301




      28.6k18114301






















          13 Answers
          13






          active

          oldest

          votes


















          103














          protected $logger;
          public function __construct(PsrLogLoggerInterface $logger)
          {
          $this->logger = $logger;
          }


          You use debug, exception, system for PSR Logger for example:



          $this->logger->info($message);
          $this->logger->debug($message);





          share|improve this answer





















          • 8





            +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

            – Alan Storm
            Dec 3 '15 at 7:21











          • You check Manager.php for following class MagentoFrameworkEvent and add this line $this->logger->debug($eventName); than after refresh page and check debug.txt file you get all evant name for specific page.

            – Pratik
            Dec 3 '15 at 7:30








          • 2





            Technically, this is the 'correct' way to instantiate a logger in your own custom classes - particularly if you intend to keep it around rather than just some quick debug. However, there are several core classes - particularly Block classes - which automatically instantiate and store a _logger property. If you extend one of these core classes then there's no need to repeat the logic. Other answers dig into creating handlers to define your own log file, but the default logs are always /var/log/system.log or /var/log/debug.log. I believe the specific logging function determines which is used.

            – Jeremy Rimpo
            Jul 6 '17 at 16:11






          • 6





            For me, the "debug" level started to work only when I enabled "Log to file" in Configuration > Advanced > Developer > Debug. Using 2.2

            – Omer Sabic
            Nov 15 '17 at 9:45





















          83














          In magento2, You can also write to the logs using the Zend library like below :



          $writer = new ZendLogWriterStream(BP . '/var/log/test.log');
          $logger = new ZendLogLogger();
          $logger->addWriter($writer);
          $logger->info('Your text message');


          Edited



          You can also print PHP objects and arrays like below :



          $logger->info(print_r($yourArray, true));





          share|improve this answer





















          • 7





            +1 Useful -- do you know if Zend logger will automatically format PHP arrays/objects etc?

            – Alan Storm
            Dec 3 '15 at 7:21






          • 1





            @AlanStorm - Yes you can, check my updated answer.!

            – Manashvi Birla
            Dec 3 '15 at 11:05






          • 2





            @Manashvibirla : PHP objects are not printing...

            – zed Blackbeard
            Mar 1 '16 at 6:43






          • 1





            @KeyurShah The solution was provided by keeping ubuntu in mind, as i was using ubuntu.! thanks for the feedback

            – Manashvi Birla
            Nov 16 '16 at 9:43






          • 3





            Several of these answers have their place and use. Obviously this solution requires almost as much code as using DI to instantiate the standard logger -- but it's a simple in-place drop-in which lets you set your own log file. Sometimes it's rather annoying to search through the standard log files - which tend to get cluttered - to find your own logs. So this is a nice 'quick' solution for that.

            – Jeremy Rimpo
            Jul 6 '17 at 16:17





















          46














          MagentoFrameworkAppObjectManager::getInstance()
          ->get(PsrLogLoggerInterface::class)->debug('message');





          share|improve this answer





















          • 5





            +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

            – Alan Storm
            Dec 3 '15 at 7:21






          • 1





            That's the correct answer.

            – medina
            May 23 '16 at 5:14






          • 4





            I would not advice to use the ObjectManager directly. Use DI instead

            – 7ochem
            Nov 4 '16 at 12:18






          • 10





            While I agree with @7ochem if you're creating a permanent logging function, it can be necessary to inject temporary logging into core (or third party) classes from time to time to debug issues. Going through the arduous process of adding a Logger class to the constructor is pointlessly over-complicated in these cases. For a simple, single-line debug function this is probably the best solution. However, you will have to deal with searching through the default log files to find your own debug output.

            – Jeremy Rimpo
            Jul 6 '17 at 16:02











          • Also keep in mind that there are several core classes - particularly Block classes - which have a _logger property you can access without instantiating a new copy.

            – Jeremy Rimpo
            Jul 6 '17 at 16:06



















          19















          Temporary print log with new file




          $writer = new ZendLogWriterStream(BP . '/var/log/logfile.log');
          $logger = new ZendLogLogger();
          $logger->addWriter($writer);
          $logger->info('Simple Text Log'); // Simple Text Log
          $logger->info('Array Log'.print_r($myArrayVar, true)); // Array Log



          Factory Method




          You need to inject PsrLogLoggerInterface class into constructor to call logger object



          protected $_logger;
          public function __construct(
          ...
          PsrLogLoggerInterface $logger
          ...
          ) {
          $this->_logger = $logger;
          }

          public function logExample() {

          //To print string Output in debug.log
          $this->_logger->addDebug('Your Text Or Variables');

          // To print array Output in system.log
          $this->_logger->log('600', print_r($yourArray, true));

          }



          Or you directly use this code in phtml file:




          To print string Output in debug.log



          MagentoFrameworkAppObjectManager::getInstance()
          ->get('PsrLogLoggerInterface')->debug('Your Message');


          To print array Output in system.log



          $myArray = array('test1'=>'123', 'test2'=>'123', 'test3'=>'123');
          $level = '100'; // use one of: 100, 200, 250, 300, 400, 500, 550, 600
          MagentoFrameworkAppObjectManager::getInstance()
          ->get('PsrLogLoggerInterface')
          ->log($level, print_r($myArray, true));





          share|improve this answer

































            10














            If you want to use default logger but custom file for logging (or other custom logic) you need to use custom logger handler:



            class Logger extends MagentoFrameworkLoggerHandlerBase
            {
            /**
            * @var string
            */
            protected $fileName = '/var/log/my-log-file.log';

            /**
            * @var int
            */
            protected $loggerType = MonologLogger::DEBUG;
            }


            Then add it as handler somewhere within your code:



            protected function addCustomLogHandler()
            {
            $logger = Data::getCustomLogger();
            if(isset($this->_logger)){
            $this->_logger->pushHandler($logger);
            }
            }


            A step back in convenience IMO






            share|improve this answer
























            • +1 Useful information, thank you! However, it's not clear how you use this logger context with the PSR-3 autoloader interface - i.e. if you're logging with $this->logger->info($message, $level); -- how do you say "use my context"?

              – Alan Storm
              Dec 3 '15 at 17:39






            • 2





              Well the thing is that all handlers that are available to Monolog are looped and first that can handle the level of record (DEBUG, INFO etc.) is used. So the only way I see to be absolutely sure that your handler is used, is to push it before you need it, so its at top of the stack and comes first in the loop. Another way would be to just SET it as handler, removing all others, but that won't be very friendly thing to do.

              – Petar Dzhambazov
              Dec 3 '15 at 18:42













            • If you try to introduce additional handlers in the 2.0.0 GA, or work with specifying the handlers in di.xml you may want to be aware of this issue github.com/magento/magento2/issues/2529 I ran into this issue trying to get a custom logger to have a custom log file handle, and a custom handler that writes some entries to a database table.

              – mttjohnson
              Dec 7 '15 at 3:47



















            5














            No, there is no direct equivalent. It's a bit complicated now.



            See: Logging to a custom file in Magento 2






            share|improve this answer





















            • 1





              +1, thank you! However -- other answers make it sound like there may be a single logger, and the extend/create a handle approach is no longer necessary. Do you know if that's true?

              – Alan Storm
              Dec 3 '15 at 7:22



















            3














            Include psr logger class in your file using use and then call addDebug() method. This will print log message in var/log/debug.log file



            use PsrLogLoggerInterface;

            class demo {
            function demo()
            {
            //EDIT: Using debug instead of addDebug for PSR compatiblity
            $this->_objectManager->get('PsrLogLoggerInterface')->debug("your message goes here");
            }

            }





            share|improve this answer





















            • 2





              you shouldn't ujse addDebug as that's not psr logger compatible. use just debug instead.

              – Maciej Paprocki
              Nov 9 '16 at 15:56



















            3














            In a simple way if you don't want to create dependency injection or anything else use below code it will store log in system.log file



            $logger = MagentoFrameworkAppObjectManager::getInstance()->get(PsrLogLoggerInterface::class);
            $logger->info('message');


            That's all..






            share|improve this answer

































              2














              If you are looking for elegant custom log handler, I recommend you to create a helper (which able to use anywhere in your project by injecting it in your constructors).



              Inspired from answer of Petar Dzhambazov and halk, ladies and gentlement I introduced you a better and shorter way instead of duplicated custom log code all the time.




              StackoverflowCoreHelperData.php




              <?php
              /**
              * Copyright © 2016 Toan Nguyen <https://nntoan.github.io>. All rights reserved.
              * See COPYING.txt for license details.
              */

              namespace StackoverflowCoreHelper;

              use MagentoFrameworkAppHelperAbstractHelper;
              use MagentoFrameworkAppHelperContext;
              use MagentoFrameworkObjectManagerInterface;
              use MonologHandlerStreamHandler;
              use MonologLogger;

              /**
              * Stackoverflow Core Helper
              *
              * @package StackoverflowCoreHelper
              * @author Toan Nguyen <https://github.com/nntoan>
              */
              class Data extends AbstractHelper
              {
              /**
              * @var MagentoFrameworkObjectManagerInterface
              */
              protected $objectManager;
              /**
              * @var PsrLogLoggerInterface
              */
              protected $defaultLogger;
              /**
              * @var string
              */
              protected $channelName;
              /**
              * @var string
              */
              protected $logFile;

              /**
              * Data constructor.
              *
              * @param Context $context Context
              * @param ObjectManagerInterface $objectManager Object manager
              */
              public function __construct(
              Context $context,
              ObjectManagerInterface $objectManager
              ) {
              parent::__construct($context);
              $this->objectManager = $objectManager;
              $this->defaultLogger = $context->getLogger();
              $this->channelName = 'stackoverflow-default-channel';
              $this->logFile = BP . '/var/log/stackoverflow.log';
              }

              /**
              * Get default/custom logger instance
              *
              * @param string $type
              * @param string|null $channelName
              * @param string|null $logFile
              *
              * @return PsrLogLoggerInterface
              */
              public function getLogger($type = 'default', $channelName = null, $logFile = null)
              {
              switch ($type) {
              case 'custom':
              $logger = $this->getCustomLogger($channelName, $logFile);
              break;
              case 'default':
              default:
              $logger = $this->getDefaultLogger();
              break;
              }

              return $logger;
              }

              /**
              * Return default logger instance
              *
              * @return PsrLogLoggerInterface
              */
              private function getDefaultLogger()
              {
              return $this->defaultLogger;
              }

              /**
              * Create new logger instance with custom channel name
              * and log file name
              *
              * @param string|null $channelName
              * @param string|null $logFile
              *
              * @return MonologLogger
              */
              private function getCustomLogger($channelName = null, $logFile = null)
              {
              if (!empty($channelName) && !empty($logFile)) {
              $this->channelName = $channelName;
              $this->logFile = BP . $logFile;
              }

              /** @var MonologLogger $logger */
              $logger = $this->objectManager->create(Logger::class, [$this->channelName]);

              /** @var MonologHandlerStreamHandler $streamHandler */
              $streamHandler = $this->objectManager->create(StreamHandler::class, [$this->logFile]);
              $logger->pushHandler($streamHandler);

              return $logger;
              }
              }


              USAGE




              VendorSomethingModelDonaldTrump.php




              <?php
              /**
              * Copyright © 2016 Toan Nguyen <https://nntoan.github.io>. All rights reserved.
              * See COPYING.txt for license details.
              */

              namespace VendorSomethingModel;

              use StackoverflowCoreHelperData as SoHelper;

              /**
              * DonaldTrump business logic file
              *
              * @package VendorSomethingModel
              * @author Toan Nguyen <https://github.com/nntoan>
              */
              class DonaldTrump
              {
              /**
              * @var PsrLogLoggerInterface
              */
              private $logger;

              const LOG_CHANNEL_NAME = 'donald-trump';
              const LOG_FILEPATH = '/var/log/donald-trump/make-america-great-again.log';

              /**
              * DonaldTrump constructor.
              *
              * @param SoHelper $soHelper
              */
              public function __construct(
              SoHelper $soHelper
              ) {
              $this->logger = $soHelper->getLogger('custom', self::LOG_CHANNEL_NAME, self::LOG_FILEPATH);
              }

              /**
              * Test my custom log
              *
              * @return void
              */
              public function test()
              {
              $this->logger->error('MAKE AMERICA GREAT AGAIN !?');
              }
              }


              As you see, whenever test() method called, the string MAKE AMERICA GREAT AGAIN !? will be log as error into a custom file (create folder automatically if doesn't exist) in <magento_dir>/var/log/donald-trump/make-america-great-again.log



              In other model, e.g HillaryClinton you can create simple declare new custom log and so on...



              Hope this helps ;)






              share|improve this answer





















              • 1





                Is this code implementing PSI? (Political Statements Injection) :P

                – 7ochem
                May 12 '17 at 14:56











              • @7ochem Oh yes, it is :v

                – Toan Nguyen
                May 14 '17 at 6:23



















              2














              There is one update for logger in 2.2. You can enable logger for production mode by run SQL:



               "INSERT INTO core_config_data (scope, scope_id, path, value) VALUES ('default', '0', 'dev/debug/debug_logging', '1');"


              Then you can use PsrLogLoggerInterface for print log just like above answers:



              protected $logger;

              public function __construct(
              PsrLogLoggerInterface $logger
              ) {
              $this->logger = $logger;
              }

              public function yourFunction() {
              $data = ["test" => "testing"];
              $this->logger->debug(var_export($data, true));
              }





              share|improve this answer
























              • thanks, and you can also use this instead of QUERY SQL: In the Magento admin panel, go to "Stores" -> "Configuration" -> "Advanced" -> "Developer" -> "Debug" -> "Log to File". Setting this to "Yes" will cause debug information to be logged to var/log/debug.log in your Magento application directory.

                – fudu
                Oct 31 '18 at 3:47



















              1















              1. Inject $logger class in constructor PsrLogLoggerInterface $logger

                This is achieved by passing $logger as argument.



              2. Initialize $logger in constructor



                $this->logger = $logger



              3. In function within the class you want to log use the below line



                $this->logger->debug($message);
                $this->logger->log($level, $message);







              share|improve this answer

































                1














                If you need it within your single class with custom log file:



                public function __construct(PsrLogLoggerInterface $logger, MagentoFrameworkAppFilesystemDirectoryList $dir) 
                {
                $this->logger = $logger;
                $this->dir = $dir;

                $this->logger->pushHandler(new MonologHandlerStreamHandler($this->dir->getRoot().'/var/log/custom.log'));
                }





                share|improve this answer































                  0














                  Place PSR logger code in your constructor:



                  protected $logger;
                  public function __construct(PsrLogLoggerInterface $logger)
                  {
                  $this->logger = $logger;
                  }


                  then you can use in your function like:



                  $this->logger->info($message);





                  share|improve this answer






















                    protected by Qaisar Satti Dec 15 '15 at 12:04



                    Thank you for your interest in this question.
                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                    Would you like to answer one of these unanswered questions instead?














                    13 Answers
                    13






                    active

                    oldest

                    votes








                    13 Answers
                    13






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    103














                    protected $logger;
                    public function __construct(PsrLogLoggerInterface $logger)
                    {
                    $this->logger = $logger;
                    }


                    You use debug, exception, system for PSR Logger for example:



                    $this->logger->info($message);
                    $this->logger->debug($message);





                    share|improve this answer





















                    • 8





                      +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                      – Alan Storm
                      Dec 3 '15 at 7:21











                    • You check Manager.php for following class MagentoFrameworkEvent and add this line $this->logger->debug($eventName); than after refresh page and check debug.txt file you get all evant name for specific page.

                      – Pratik
                      Dec 3 '15 at 7:30








                    • 2





                      Technically, this is the 'correct' way to instantiate a logger in your own custom classes - particularly if you intend to keep it around rather than just some quick debug. However, there are several core classes - particularly Block classes - which automatically instantiate and store a _logger property. If you extend one of these core classes then there's no need to repeat the logic. Other answers dig into creating handlers to define your own log file, but the default logs are always /var/log/system.log or /var/log/debug.log. I believe the specific logging function determines which is used.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:11






                    • 6





                      For me, the "debug" level started to work only when I enabled "Log to file" in Configuration > Advanced > Developer > Debug. Using 2.2

                      – Omer Sabic
                      Nov 15 '17 at 9:45


















                    103














                    protected $logger;
                    public function __construct(PsrLogLoggerInterface $logger)
                    {
                    $this->logger = $logger;
                    }


                    You use debug, exception, system for PSR Logger for example:



                    $this->logger->info($message);
                    $this->logger->debug($message);





                    share|improve this answer





















                    • 8





                      +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                      – Alan Storm
                      Dec 3 '15 at 7:21











                    • You check Manager.php for following class MagentoFrameworkEvent and add this line $this->logger->debug($eventName); than after refresh page and check debug.txt file you get all evant name for specific page.

                      – Pratik
                      Dec 3 '15 at 7:30








                    • 2





                      Technically, this is the 'correct' way to instantiate a logger in your own custom classes - particularly if you intend to keep it around rather than just some quick debug. However, there are several core classes - particularly Block classes - which automatically instantiate and store a _logger property. If you extend one of these core classes then there's no need to repeat the logic. Other answers dig into creating handlers to define your own log file, but the default logs are always /var/log/system.log or /var/log/debug.log. I believe the specific logging function determines which is used.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:11






                    • 6





                      For me, the "debug" level started to work only when I enabled "Log to file" in Configuration > Advanced > Developer > Debug. Using 2.2

                      – Omer Sabic
                      Nov 15 '17 at 9:45
















                    103












                    103








                    103







                    protected $logger;
                    public function __construct(PsrLogLoggerInterface $logger)
                    {
                    $this->logger = $logger;
                    }


                    You use debug, exception, system for PSR Logger for example:



                    $this->logger->info($message);
                    $this->logger->debug($message);





                    share|improve this answer















                    protected $logger;
                    public function __construct(PsrLogLoggerInterface $logger)
                    {
                    $this->logger = $logger;
                    }


                    You use debug, exception, system for PSR Logger for example:



                    $this->logger->info($message);
                    $this->logger->debug($message);






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Oct 11 '17 at 21:35









                    Rafael Corrêa Gomes

                    4,28222962




                    4,28222962










                    answered Dec 3 '15 at 5:14









                    PratikPratik

                    2,07351342




                    2,07351342








                    • 8





                      +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                      – Alan Storm
                      Dec 3 '15 at 7:21











                    • You check Manager.php for following class MagentoFrameworkEvent and add this line $this->logger->debug($eventName); than after refresh page and check debug.txt file you get all evant name for specific page.

                      – Pratik
                      Dec 3 '15 at 7:30








                    • 2





                      Technically, this is the 'correct' way to instantiate a logger in your own custom classes - particularly if you intend to keep it around rather than just some quick debug. However, there are several core classes - particularly Block classes - which automatically instantiate and store a _logger property. If you extend one of these core classes then there's no need to repeat the logic. Other answers dig into creating handlers to define your own log file, but the default logs are always /var/log/system.log or /var/log/debug.log. I believe the specific logging function determines which is used.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:11






                    • 6





                      For me, the "debug" level started to work only when I enabled "Log to file" in Configuration > Advanced > Developer > Debug. Using 2.2

                      – Omer Sabic
                      Nov 15 '17 at 9:45
















                    • 8





                      +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                      – Alan Storm
                      Dec 3 '15 at 7:21











                    • You check Manager.php for following class MagentoFrameworkEvent and add this line $this->logger->debug($eventName); than after refresh page and check debug.txt file you get all evant name for specific page.

                      – Pratik
                      Dec 3 '15 at 7:30








                    • 2





                      Technically, this is the 'correct' way to instantiate a logger in your own custom classes - particularly if you intend to keep it around rather than just some quick debug. However, there are several core classes - particularly Block classes - which automatically instantiate and store a _logger property. If you extend one of these core classes then there's no need to repeat the logic. Other answers dig into creating handlers to define your own log file, but the default logs are always /var/log/system.log or /var/log/debug.log. I believe the specific logging function determines which is used.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:11






                    • 6





                      For me, the "debug" level started to work only when I enabled "Log to file" in Configuration > Advanced > Developer > Debug. Using 2.2

                      – Omer Sabic
                      Nov 15 '17 at 9:45










                    8




                    8





                    +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                    – Alan Storm
                    Dec 3 '15 at 7:21





                    +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                    – Alan Storm
                    Dec 3 '15 at 7:21













                    You check Manager.php for following class MagentoFrameworkEvent and add this line $this->logger->debug($eventName); than after refresh page and check debug.txt file you get all evant name for specific page.

                    – Pratik
                    Dec 3 '15 at 7:30







                    You check Manager.php for following class MagentoFrameworkEvent and add this line $this->logger->debug($eventName); than after refresh page and check debug.txt file you get all evant name for specific page.

                    – Pratik
                    Dec 3 '15 at 7:30






                    2




                    2





                    Technically, this is the 'correct' way to instantiate a logger in your own custom classes - particularly if you intend to keep it around rather than just some quick debug. However, there are several core classes - particularly Block classes - which automatically instantiate and store a _logger property. If you extend one of these core classes then there's no need to repeat the logic. Other answers dig into creating handlers to define your own log file, but the default logs are always /var/log/system.log or /var/log/debug.log. I believe the specific logging function determines which is used.

                    – Jeremy Rimpo
                    Jul 6 '17 at 16:11





                    Technically, this is the 'correct' way to instantiate a logger in your own custom classes - particularly if you intend to keep it around rather than just some quick debug. However, there are several core classes - particularly Block classes - which automatically instantiate and store a _logger property. If you extend one of these core classes then there's no need to repeat the logic. Other answers dig into creating handlers to define your own log file, but the default logs are always /var/log/system.log or /var/log/debug.log. I believe the specific logging function determines which is used.

                    – Jeremy Rimpo
                    Jul 6 '17 at 16:11




                    6




                    6





                    For me, the "debug" level started to work only when I enabled "Log to file" in Configuration > Advanced > Developer > Debug. Using 2.2

                    – Omer Sabic
                    Nov 15 '17 at 9:45







                    For me, the "debug" level started to work only when I enabled "Log to file" in Configuration > Advanced > Developer > Debug. Using 2.2

                    – Omer Sabic
                    Nov 15 '17 at 9:45















                    83














                    In magento2, You can also write to the logs using the Zend library like below :



                    $writer = new ZendLogWriterStream(BP . '/var/log/test.log');
                    $logger = new ZendLogLogger();
                    $logger->addWriter($writer);
                    $logger->info('Your text message');


                    Edited



                    You can also print PHP objects and arrays like below :



                    $logger->info(print_r($yourArray, true));





                    share|improve this answer





















                    • 7





                      +1 Useful -- do you know if Zend logger will automatically format PHP arrays/objects etc?

                      – Alan Storm
                      Dec 3 '15 at 7:21






                    • 1





                      @AlanStorm - Yes you can, check my updated answer.!

                      – Manashvi Birla
                      Dec 3 '15 at 11:05






                    • 2





                      @Manashvibirla : PHP objects are not printing...

                      – zed Blackbeard
                      Mar 1 '16 at 6:43






                    • 1





                      @KeyurShah The solution was provided by keeping ubuntu in mind, as i was using ubuntu.! thanks for the feedback

                      – Manashvi Birla
                      Nov 16 '16 at 9:43






                    • 3





                      Several of these answers have their place and use. Obviously this solution requires almost as much code as using DI to instantiate the standard logger -- but it's a simple in-place drop-in which lets you set your own log file. Sometimes it's rather annoying to search through the standard log files - which tend to get cluttered - to find your own logs. So this is a nice 'quick' solution for that.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:17


















                    83














                    In magento2, You can also write to the logs using the Zend library like below :



                    $writer = new ZendLogWriterStream(BP . '/var/log/test.log');
                    $logger = new ZendLogLogger();
                    $logger->addWriter($writer);
                    $logger->info('Your text message');


                    Edited



                    You can also print PHP objects and arrays like below :



                    $logger->info(print_r($yourArray, true));





                    share|improve this answer





















                    • 7





                      +1 Useful -- do you know if Zend logger will automatically format PHP arrays/objects etc?

                      – Alan Storm
                      Dec 3 '15 at 7:21






                    • 1





                      @AlanStorm - Yes you can, check my updated answer.!

                      – Manashvi Birla
                      Dec 3 '15 at 11:05






                    • 2





                      @Manashvibirla : PHP objects are not printing...

                      – zed Blackbeard
                      Mar 1 '16 at 6:43






                    • 1





                      @KeyurShah The solution was provided by keeping ubuntu in mind, as i was using ubuntu.! thanks for the feedback

                      – Manashvi Birla
                      Nov 16 '16 at 9:43






                    • 3





                      Several of these answers have their place and use. Obviously this solution requires almost as much code as using DI to instantiate the standard logger -- but it's a simple in-place drop-in which lets you set your own log file. Sometimes it's rather annoying to search through the standard log files - which tend to get cluttered - to find your own logs. So this is a nice 'quick' solution for that.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:17
















                    83












                    83








                    83







                    In magento2, You can also write to the logs using the Zend library like below :



                    $writer = new ZendLogWriterStream(BP . '/var/log/test.log');
                    $logger = new ZendLogLogger();
                    $logger->addWriter($writer);
                    $logger->info('Your text message');


                    Edited



                    You can also print PHP objects and arrays like below :



                    $logger->info(print_r($yourArray, true));





                    share|improve this answer















                    In magento2, You can also write to the logs using the Zend library like below :



                    $writer = new ZendLogWriterStream(BP . '/var/log/test.log');
                    $logger = new ZendLogLogger();
                    $logger->addWriter($writer);
                    $logger->info('Your text message');


                    Edited



                    You can also print PHP objects and arrays like below :



                    $logger->info(print_r($yourArray, true));






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 3 '15 at 11:05

























                    answered Dec 3 '15 at 5:11









                    Manashvi BirlaManashvi Birla

                    6,11241840




                    6,11241840








                    • 7





                      +1 Useful -- do you know if Zend logger will automatically format PHP arrays/objects etc?

                      – Alan Storm
                      Dec 3 '15 at 7:21






                    • 1





                      @AlanStorm - Yes you can, check my updated answer.!

                      – Manashvi Birla
                      Dec 3 '15 at 11:05






                    • 2





                      @Manashvibirla : PHP objects are not printing...

                      – zed Blackbeard
                      Mar 1 '16 at 6:43






                    • 1





                      @KeyurShah The solution was provided by keeping ubuntu in mind, as i was using ubuntu.! thanks for the feedback

                      – Manashvi Birla
                      Nov 16 '16 at 9:43






                    • 3





                      Several of these answers have their place and use. Obviously this solution requires almost as much code as using DI to instantiate the standard logger -- but it's a simple in-place drop-in which lets you set your own log file. Sometimes it's rather annoying to search through the standard log files - which tend to get cluttered - to find your own logs. So this is a nice 'quick' solution for that.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:17
















                    • 7





                      +1 Useful -- do you know if Zend logger will automatically format PHP arrays/objects etc?

                      – Alan Storm
                      Dec 3 '15 at 7:21






                    • 1





                      @AlanStorm - Yes you can, check my updated answer.!

                      – Manashvi Birla
                      Dec 3 '15 at 11:05






                    • 2





                      @Manashvibirla : PHP objects are not printing...

                      – zed Blackbeard
                      Mar 1 '16 at 6:43






                    • 1





                      @KeyurShah The solution was provided by keeping ubuntu in mind, as i was using ubuntu.! thanks for the feedback

                      – Manashvi Birla
                      Nov 16 '16 at 9:43






                    • 3





                      Several of these answers have their place and use. Obviously this solution requires almost as much code as using DI to instantiate the standard logger -- but it's a simple in-place drop-in which lets you set your own log file. Sometimes it's rather annoying to search through the standard log files - which tend to get cluttered - to find your own logs. So this is a nice 'quick' solution for that.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:17










                    7




                    7





                    +1 Useful -- do you know if Zend logger will automatically format PHP arrays/objects etc?

                    – Alan Storm
                    Dec 3 '15 at 7:21





                    +1 Useful -- do you know if Zend logger will automatically format PHP arrays/objects etc?

                    – Alan Storm
                    Dec 3 '15 at 7:21




                    1




                    1





                    @AlanStorm - Yes you can, check my updated answer.!

                    – Manashvi Birla
                    Dec 3 '15 at 11:05





                    @AlanStorm - Yes you can, check my updated answer.!

                    – Manashvi Birla
                    Dec 3 '15 at 11:05




                    2




                    2





                    @Manashvibirla : PHP objects are not printing...

                    – zed Blackbeard
                    Mar 1 '16 at 6:43





                    @Manashvibirla : PHP objects are not printing...

                    – zed Blackbeard
                    Mar 1 '16 at 6:43




                    1




                    1





                    @KeyurShah The solution was provided by keeping ubuntu in mind, as i was using ubuntu.! thanks for the feedback

                    – Manashvi Birla
                    Nov 16 '16 at 9:43





                    @KeyurShah The solution was provided by keeping ubuntu in mind, as i was using ubuntu.! thanks for the feedback

                    – Manashvi Birla
                    Nov 16 '16 at 9:43




                    3




                    3





                    Several of these answers have their place and use. Obviously this solution requires almost as much code as using DI to instantiate the standard logger -- but it's a simple in-place drop-in which lets you set your own log file. Sometimes it's rather annoying to search through the standard log files - which tend to get cluttered - to find your own logs. So this is a nice 'quick' solution for that.

                    – Jeremy Rimpo
                    Jul 6 '17 at 16:17







                    Several of these answers have their place and use. Obviously this solution requires almost as much code as using DI to instantiate the standard logger -- but it's a simple in-place drop-in which lets you set your own log file. Sometimes it's rather annoying to search through the standard log files - which tend to get cluttered - to find your own logs. So this is a nice 'quick' solution for that.

                    – Jeremy Rimpo
                    Jul 6 '17 at 16:17













                    46














                    MagentoFrameworkAppObjectManager::getInstance()
                    ->get(PsrLogLoggerInterface::class)->debug('message');





                    share|improve this answer





















                    • 5





                      +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                      – Alan Storm
                      Dec 3 '15 at 7:21






                    • 1





                      That's the correct answer.

                      – medina
                      May 23 '16 at 5:14






                    • 4





                      I would not advice to use the ObjectManager directly. Use DI instead

                      – 7ochem
                      Nov 4 '16 at 12:18






                    • 10





                      While I agree with @7ochem if you're creating a permanent logging function, it can be necessary to inject temporary logging into core (or third party) classes from time to time to debug issues. Going through the arduous process of adding a Logger class to the constructor is pointlessly over-complicated in these cases. For a simple, single-line debug function this is probably the best solution. However, you will have to deal with searching through the default log files to find your own debug output.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:02











                    • Also keep in mind that there are several core classes - particularly Block classes - which have a _logger property you can access without instantiating a new copy.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:06
















                    46














                    MagentoFrameworkAppObjectManager::getInstance()
                    ->get(PsrLogLoggerInterface::class)->debug('message');





                    share|improve this answer





















                    • 5





                      +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                      – Alan Storm
                      Dec 3 '15 at 7:21






                    • 1





                      That's the correct answer.

                      – medina
                      May 23 '16 at 5:14






                    • 4





                      I would not advice to use the ObjectManager directly. Use DI instead

                      – 7ochem
                      Nov 4 '16 at 12:18






                    • 10





                      While I agree with @7ochem if you're creating a permanent logging function, it can be necessary to inject temporary logging into core (or third party) classes from time to time to debug issues. Going through the arduous process of adding a Logger class to the constructor is pointlessly over-complicated in these cases. For a simple, single-line debug function this is probably the best solution. However, you will have to deal with searching through the default log files to find your own debug output.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:02











                    • Also keep in mind that there are several core classes - particularly Block classes - which have a _logger property you can access without instantiating a new copy.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:06














                    46












                    46








                    46







                    MagentoFrameworkAppObjectManager::getInstance()
                    ->get(PsrLogLoggerInterface::class)->debug('message');





                    share|improve this answer















                    MagentoFrameworkAppObjectManager::getInstance()
                    ->get(PsrLogLoggerInterface::class)->debug('message');






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 12 '17 at 13:28









                    7ochem

                    5,72193668




                    5,72193668










                    answered Dec 3 '15 at 4:42









                    Mage2.PROMage2.PRO

                    3,55211319




                    3,55211319








                    • 5





                      +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                      – Alan Storm
                      Dec 3 '15 at 7:21






                    • 1





                      That's the correct answer.

                      – medina
                      May 23 '16 at 5:14






                    • 4





                      I would not advice to use the ObjectManager directly. Use DI instead

                      – 7ochem
                      Nov 4 '16 at 12:18






                    • 10





                      While I agree with @7ochem if you're creating a permanent logging function, it can be necessary to inject temporary logging into core (or third party) classes from time to time to debug issues. Going through the arduous process of adding a Logger class to the constructor is pointlessly over-complicated in these cases. For a simple, single-line debug function this is probably the best solution. However, you will have to deal with searching through the default log files to find your own debug output.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:02











                    • Also keep in mind that there are several core classes - particularly Block classes - which have a _logger property you can access without instantiating a new copy.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:06














                    • 5





                      +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                      – Alan Storm
                      Dec 3 '15 at 7:21






                    • 1





                      That's the correct answer.

                      – medina
                      May 23 '16 at 5:14






                    • 4





                      I would not advice to use the ObjectManager directly. Use DI instead

                      – 7ochem
                      Nov 4 '16 at 12:18






                    • 10





                      While I agree with @7ochem if you're creating a permanent logging function, it can be necessary to inject temporary logging into core (or third party) classes from time to time to debug issues. Going through the arduous process of adding a Logger class to the constructor is pointlessly over-complicated in these cases. For a simple, single-line debug function this is probably the best solution. However, you will have to deal with searching through the default log files to find your own debug output.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:02











                    • Also keep in mind that there are several core classes - particularly Block classes - which have a _logger property you can access without instantiating a new copy.

                      – Jeremy Rimpo
                      Jul 6 '17 at 16:06








                    5




                    5





                    +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                    – Alan Storm
                    Dec 3 '15 at 7:21





                    +1 Thank you, that's a useful interface/class/type to know about -- but it's not clear from your answer where the information will be logged and how (if possible) to change that location.

                    – Alan Storm
                    Dec 3 '15 at 7:21




                    1




                    1





                    That's the correct answer.

                    – medina
                    May 23 '16 at 5:14





                    That's the correct answer.

                    – medina
                    May 23 '16 at 5:14




                    4




                    4





                    I would not advice to use the ObjectManager directly. Use DI instead

                    – 7ochem
                    Nov 4 '16 at 12:18





                    I would not advice to use the ObjectManager directly. Use DI instead

                    – 7ochem
                    Nov 4 '16 at 12:18




                    10




                    10





                    While I agree with @7ochem if you're creating a permanent logging function, it can be necessary to inject temporary logging into core (or third party) classes from time to time to debug issues. Going through the arduous process of adding a Logger class to the constructor is pointlessly over-complicated in these cases. For a simple, single-line debug function this is probably the best solution. However, you will have to deal with searching through the default log files to find your own debug output.

                    – Jeremy Rimpo
                    Jul 6 '17 at 16:02





                    While I agree with @7ochem if you're creating a permanent logging function, it can be necessary to inject temporary logging into core (or third party) classes from time to time to debug issues. Going through the arduous process of adding a Logger class to the constructor is pointlessly over-complicated in these cases. For a simple, single-line debug function this is probably the best solution. However, you will have to deal with searching through the default log files to find your own debug output.

                    – Jeremy Rimpo
                    Jul 6 '17 at 16:02













                    Also keep in mind that there are several core classes - particularly Block classes - which have a _logger property you can access without instantiating a new copy.

                    – Jeremy Rimpo
                    Jul 6 '17 at 16:06





                    Also keep in mind that there are several core classes - particularly Block classes - which have a _logger property you can access without instantiating a new copy.

                    – Jeremy Rimpo
                    Jul 6 '17 at 16:06











                    19















                    Temporary print log with new file




                    $writer = new ZendLogWriterStream(BP . '/var/log/logfile.log');
                    $logger = new ZendLogLogger();
                    $logger->addWriter($writer);
                    $logger->info('Simple Text Log'); // Simple Text Log
                    $logger->info('Array Log'.print_r($myArrayVar, true)); // Array Log



                    Factory Method




                    You need to inject PsrLogLoggerInterface class into constructor to call logger object



                    protected $_logger;
                    public function __construct(
                    ...
                    PsrLogLoggerInterface $logger
                    ...
                    ) {
                    $this->_logger = $logger;
                    }

                    public function logExample() {

                    //To print string Output in debug.log
                    $this->_logger->addDebug('Your Text Or Variables');

                    // To print array Output in system.log
                    $this->_logger->log('600', print_r($yourArray, true));

                    }



                    Or you directly use this code in phtml file:




                    To print string Output in debug.log



                    MagentoFrameworkAppObjectManager::getInstance()
                    ->get('PsrLogLoggerInterface')->debug('Your Message');


                    To print array Output in system.log



                    $myArray = array('test1'=>'123', 'test2'=>'123', 'test3'=>'123');
                    $level = '100'; // use one of: 100, 200, 250, 300, 400, 500, 550, 600
                    MagentoFrameworkAppObjectManager::getInstance()
                    ->get('PsrLogLoggerInterface')
                    ->log($level, print_r($myArray, true));





                    share|improve this answer






























                      19















                      Temporary print log with new file




                      $writer = new ZendLogWriterStream(BP . '/var/log/logfile.log');
                      $logger = new ZendLogLogger();
                      $logger->addWriter($writer);
                      $logger->info('Simple Text Log'); // Simple Text Log
                      $logger->info('Array Log'.print_r($myArrayVar, true)); // Array Log



                      Factory Method




                      You need to inject PsrLogLoggerInterface class into constructor to call logger object



                      protected $_logger;
                      public function __construct(
                      ...
                      PsrLogLoggerInterface $logger
                      ...
                      ) {
                      $this->_logger = $logger;
                      }

                      public function logExample() {

                      //To print string Output in debug.log
                      $this->_logger->addDebug('Your Text Or Variables');

                      // To print array Output in system.log
                      $this->_logger->log('600', print_r($yourArray, true));

                      }



                      Or you directly use this code in phtml file:




                      To print string Output in debug.log



                      MagentoFrameworkAppObjectManager::getInstance()
                      ->get('PsrLogLoggerInterface')->debug('Your Message');


                      To print array Output in system.log



                      $myArray = array('test1'=>'123', 'test2'=>'123', 'test3'=>'123');
                      $level = '100'; // use one of: 100, 200, 250, 300, 400, 500, 550, 600
                      MagentoFrameworkAppObjectManager::getInstance()
                      ->get('PsrLogLoggerInterface')
                      ->log($level, print_r($myArray, true));





                      share|improve this answer




























                        19












                        19








                        19








                        Temporary print log with new file




                        $writer = new ZendLogWriterStream(BP . '/var/log/logfile.log');
                        $logger = new ZendLogLogger();
                        $logger->addWriter($writer);
                        $logger->info('Simple Text Log'); // Simple Text Log
                        $logger->info('Array Log'.print_r($myArrayVar, true)); // Array Log



                        Factory Method




                        You need to inject PsrLogLoggerInterface class into constructor to call logger object



                        protected $_logger;
                        public function __construct(
                        ...
                        PsrLogLoggerInterface $logger
                        ...
                        ) {
                        $this->_logger = $logger;
                        }

                        public function logExample() {

                        //To print string Output in debug.log
                        $this->_logger->addDebug('Your Text Or Variables');

                        // To print array Output in system.log
                        $this->_logger->log('600', print_r($yourArray, true));

                        }



                        Or you directly use this code in phtml file:




                        To print string Output in debug.log



                        MagentoFrameworkAppObjectManager::getInstance()
                        ->get('PsrLogLoggerInterface')->debug('Your Message');


                        To print array Output in system.log



                        $myArray = array('test1'=>'123', 'test2'=>'123', 'test3'=>'123');
                        $level = '100'; // use one of: 100, 200, 250, 300, 400, 500, 550, 600
                        MagentoFrameworkAppObjectManager::getInstance()
                        ->get('PsrLogLoggerInterface')
                        ->log($level, print_r($myArray, true));





                        share|improve this answer
















                        Temporary print log with new file




                        $writer = new ZendLogWriterStream(BP . '/var/log/logfile.log');
                        $logger = new ZendLogLogger();
                        $logger->addWriter($writer);
                        $logger->info('Simple Text Log'); // Simple Text Log
                        $logger->info('Array Log'.print_r($myArrayVar, true)); // Array Log



                        Factory Method




                        You need to inject PsrLogLoggerInterface class into constructor to call logger object



                        protected $_logger;
                        public function __construct(
                        ...
                        PsrLogLoggerInterface $logger
                        ...
                        ) {
                        $this->_logger = $logger;
                        }

                        public function logExample() {

                        //To print string Output in debug.log
                        $this->_logger->addDebug('Your Text Or Variables');

                        // To print array Output in system.log
                        $this->_logger->log('600', print_r($yourArray, true));

                        }



                        Or you directly use this code in phtml file:




                        To print string Output in debug.log



                        MagentoFrameworkAppObjectManager::getInstance()
                        ->get('PsrLogLoggerInterface')->debug('Your Message');


                        To print array Output in system.log



                        $myArray = array('test1'=>'123', 'test2'=>'123', 'test3'=>'123');
                        $level = '100'; // use one of: 100, 200, 250, 300, 400, 500, 550, 600
                        MagentoFrameworkAppObjectManager::getInstance()
                        ->get('PsrLogLoggerInterface')
                        ->log($level, print_r($myArray, true));






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Dec 19 '17 at 12:44

























                        answered Jan 13 '17 at 7:27









                        Prince PatelPrince Patel

                        13.3k54676




                        13.3k54676























                            10














                            If you want to use default logger but custom file for logging (or other custom logic) you need to use custom logger handler:



                            class Logger extends MagentoFrameworkLoggerHandlerBase
                            {
                            /**
                            * @var string
                            */
                            protected $fileName = '/var/log/my-log-file.log';

                            /**
                            * @var int
                            */
                            protected $loggerType = MonologLogger::DEBUG;
                            }


                            Then add it as handler somewhere within your code:



                            protected function addCustomLogHandler()
                            {
                            $logger = Data::getCustomLogger();
                            if(isset($this->_logger)){
                            $this->_logger->pushHandler($logger);
                            }
                            }


                            A step back in convenience IMO






                            share|improve this answer
























                            • +1 Useful information, thank you! However, it's not clear how you use this logger context with the PSR-3 autoloader interface - i.e. if you're logging with $this->logger->info($message, $level); -- how do you say "use my context"?

                              – Alan Storm
                              Dec 3 '15 at 17:39






                            • 2





                              Well the thing is that all handlers that are available to Monolog are looped and first that can handle the level of record (DEBUG, INFO etc.) is used. So the only way I see to be absolutely sure that your handler is used, is to push it before you need it, so its at top of the stack and comes first in the loop. Another way would be to just SET it as handler, removing all others, but that won't be very friendly thing to do.

                              – Petar Dzhambazov
                              Dec 3 '15 at 18:42













                            • If you try to introduce additional handlers in the 2.0.0 GA, or work with specifying the handlers in di.xml you may want to be aware of this issue github.com/magento/magento2/issues/2529 I ran into this issue trying to get a custom logger to have a custom log file handle, and a custom handler that writes some entries to a database table.

                              – mttjohnson
                              Dec 7 '15 at 3:47
















                            10














                            If you want to use default logger but custom file for logging (or other custom logic) you need to use custom logger handler:



                            class Logger extends MagentoFrameworkLoggerHandlerBase
                            {
                            /**
                            * @var string
                            */
                            protected $fileName = '/var/log/my-log-file.log';

                            /**
                            * @var int
                            */
                            protected $loggerType = MonologLogger::DEBUG;
                            }


                            Then add it as handler somewhere within your code:



                            protected function addCustomLogHandler()
                            {
                            $logger = Data::getCustomLogger();
                            if(isset($this->_logger)){
                            $this->_logger->pushHandler($logger);
                            }
                            }


                            A step back in convenience IMO






                            share|improve this answer
























                            • +1 Useful information, thank you! However, it's not clear how you use this logger context with the PSR-3 autoloader interface - i.e. if you're logging with $this->logger->info($message, $level); -- how do you say "use my context"?

                              – Alan Storm
                              Dec 3 '15 at 17:39






                            • 2





                              Well the thing is that all handlers that are available to Monolog are looped and first that can handle the level of record (DEBUG, INFO etc.) is used. So the only way I see to be absolutely sure that your handler is used, is to push it before you need it, so its at top of the stack and comes first in the loop. Another way would be to just SET it as handler, removing all others, but that won't be very friendly thing to do.

                              – Petar Dzhambazov
                              Dec 3 '15 at 18:42













                            • If you try to introduce additional handlers in the 2.0.0 GA, or work with specifying the handlers in di.xml you may want to be aware of this issue github.com/magento/magento2/issues/2529 I ran into this issue trying to get a custom logger to have a custom log file handle, and a custom handler that writes some entries to a database table.

                              – mttjohnson
                              Dec 7 '15 at 3:47














                            10












                            10








                            10







                            If you want to use default logger but custom file for logging (or other custom logic) you need to use custom logger handler:



                            class Logger extends MagentoFrameworkLoggerHandlerBase
                            {
                            /**
                            * @var string
                            */
                            protected $fileName = '/var/log/my-log-file.log';

                            /**
                            * @var int
                            */
                            protected $loggerType = MonologLogger::DEBUG;
                            }


                            Then add it as handler somewhere within your code:



                            protected function addCustomLogHandler()
                            {
                            $logger = Data::getCustomLogger();
                            if(isset($this->_logger)){
                            $this->_logger->pushHandler($logger);
                            }
                            }


                            A step back in convenience IMO






                            share|improve this answer













                            If you want to use default logger but custom file for logging (or other custom logic) you need to use custom logger handler:



                            class Logger extends MagentoFrameworkLoggerHandlerBase
                            {
                            /**
                            * @var string
                            */
                            protected $fileName = '/var/log/my-log-file.log';

                            /**
                            * @var int
                            */
                            protected $loggerType = MonologLogger::DEBUG;
                            }


                            Then add it as handler somewhere within your code:



                            protected function addCustomLogHandler()
                            {
                            $logger = Data::getCustomLogger();
                            if(isset($this->_logger)){
                            $this->_logger->pushHandler($logger);
                            }
                            }


                            A step back in convenience IMO







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 3 '15 at 17:28









                            Petar DzhambazovPetar Dzhambazov

                            1,258914




                            1,258914













                            • +1 Useful information, thank you! However, it's not clear how you use this logger context with the PSR-3 autoloader interface - i.e. if you're logging with $this->logger->info($message, $level); -- how do you say "use my context"?

                              – Alan Storm
                              Dec 3 '15 at 17:39






                            • 2





                              Well the thing is that all handlers that are available to Monolog are looped and first that can handle the level of record (DEBUG, INFO etc.) is used. So the only way I see to be absolutely sure that your handler is used, is to push it before you need it, so its at top of the stack and comes first in the loop. Another way would be to just SET it as handler, removing all others, but that won't be very friendly thing to do.

                              – Petar Dzhambazov
                              Dec 3 '15 at 18:42













                            • If you try to introduce additional handlers in the 2.0.0 GA, or work with specifying the handlers in di.xml you may want to be aware of this issue github.com/magento/magento2/issues/2529 I ran into this issue trying to get a custom logger to have a custom log file handle, and a custom handler that writes some entries to a database table.

                              – mttjohnson
                              Dec 7 '15 at 3:47



















                            • +1 Useful information, thank you! However, it's not clear how you use this logger context with the PSR-3 autoloader interface - i.e. if you're logging with $this->logger->info($message, $level); -- how do you say "use my context"?

                              – Alan Storm
                              Dec 3 '15 at 17:39






                            • 2





                              Well the thing is that all handlers that are available to Monolog are looped and first that can handle the level of record (DEBUG, INFO etc.) is used. So the only way I see to be absolutely sure that your handler is used, is to push it before you need it, so its at top of the stack and comes first in the loop. Another way would be to just SET it as handler, removing all others, but that won't be very friendly thing to do.

                              – Petar Dzhambazov
                              Dec 3 '15 at 18:42













                            • If you try to introduce additional handlers in the 2.0.0 GA, or work with specifying the handlers in di.xml you may want to be aware of this issue github.com/magento/magento2/issues/2529 I ran into this issue trying to get a custom logger to have a custom log file handle, and a custom handler that writes some entries to a database table.

                              – mttjohnson
                              Dec 7 '15 at 3:47

















                            +1 Useful information, thank you! However, it's not clear how you use this logger context with the PSR-3 autoloader interface - i.e. if you're logging with $this->logger->info($message, $level); -- how do you say "use my context"?

                            – Alan Storm
                            Dec 3 '15 at 17:39





                            +1 Useful information, thank you! However, it's not clear how you use this logger context with the PSR-3 autoloader interface - i.e. if you're logging with $this->logger->info($message, $level); -- how do you say "use my context"?

                            – Alan Storm
                            Dec 3 '15 at 17:39




                            2




                            2





                            Well the thing is that all handlers that are available to Monolog are looped and first that can handle the level of record (DEBUG, INFO etc.) is used. So the only way I see to be absolutely sure that your handler is used, is to push it before you need it, so its at top of the stack and comes first in the loop. Another way would be to just SET it as handler, removing all others, but that won't be very friendly thing to do.

                            – Petar Dzhambazov
                            Dec 3 '15 at 18:42







                            Well the thing is that all handlers that are available to Monolog are looped and first that can handle the level of record (DEBUG, INFO etc.) is used. So the only way I see to be absolutely sure that your handler is used, is to push it before you need it, so its at top of the stack and comes first in the loop. Another way would be to just SET it as handler, removing all others, but that won't be very friendly thing to do.

                            – Petar Dzhambazov
                            Dec 3 '15 at 18:42















                            If you try to introduce additional handlers in the 2.0.0 GA, or work with specifying the handlers in di.xml you may want to be aware of this issue github.com/magento/magento2/issues/2529 I ran into this issue trying to get a custom logger to have a custom log file handle, and a custom handler that writes some entries to a database table.

                            – mttjohnson
                            Dec 7 '15 at 3:47





                            If you try to introduce additional handlers in the 2.0.0 GA, or work with specifying the handlers in di.xml you may want to be aware of this issue github.com/magento/magento2/issues/2529 I ran into this issue trying to get a custom logger to have a custom log file handle, and a custom handler that writes some entries to a database table.

                            – mttjohnson
                            Dec 7 '15 at 3:47











                            5














                            No, there is no direct equivalent. It's a bit complicated now.



                            See: Logging to a custom file in Magento 2






                            share|improve this answer





















                            • 1





                              +1, thank you! However -- other answers make it sound like there may be a single logger, and the extend/create a handle approach is no longer necessary. Do you know if that's true?

                              – Alan Storm
                              Dec 3 '15 at 7:22
















                            5














                            No, there is no direct equivalent. It's a bit complicated now.



                            See: Logging to a custom file in Magento 2






                            share|improve this answer





















                            • 1





                              +1, thank you! However -- other answers make it sound like there may be a single logger, and the extend/create a handle approach is no longer necessary. Do you know if that's true?

                              – Alan Storm
                              Dec 3 '15 at 7:22














                            5












                            5








                            5







                            No, there is no direct equivalent. It's a bit complicated now.



                            See: Logging to a custom file in Magento 2






                            share|improve this answer















                            No, there is no direct equivalent. It's a bit complicated now.



                            See: Logging to a custom file in Magento 2







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Apr 13 '17 at 12:55









                            Community

                            1




                            1










                            answered Dec 3 '15 at 4:28









                            Ryan HoerrRyan Hoerr

                            8,38433042




                            8,38433042








                            • 1





                              +1, thank you! However -- other answers make it sound like there may be a single logger, and the extend/create a handle approach is no longer necessary. Do you know if that's true?

                              – Alan Storm
                              Dec 3 '15 at 7:22














                            • 1





                              +1, thank you! However -- other answers make it sound like there may be a single logger, and the extend/create a handle approach is no longer necessary. Do you know if that's true?

                              – Alan Storm
                              Dec 3 '15 at 7:22








                            1




                            1





                            +1, thank you! However -- other answers make it sound like there may be a single logger, and the extend/create a handle approach is no longer necessary. Do you know if that's true?

                            – Alan Storm
                            Dec 3 '15 at 7:22





                            +1, thank you! However -- other answers make it sound like there may be a single logger, and the extend/create a handle approach is no longer necessary. Do you know if that's true?

                            – Alan Storm
                            Dec 3 '15 at 7:22











                            3














                            Include psr logger class in your file using use and then call addDebug() method. This will print log message in var/log/debug.log file



                            use PsrLogLoggerInterface;

                            class demo {
                            function demo()
                            {
                            //EDIT: Using debug instead of addDebug for PSR compatiblity
                            $this->_objectManager->get('PsrLogLoggerInterface')->debug("your message goes here");
                            }

                            }





                            share|improve this answer





















                            • 2





                              you shouldn't ujse addDebug as that's not psr logger compatible. use just debug instead.

                              – Maciej Paprocki
                              Nov 9 '16 at 15:56
















                            3














                            Include psr logger class in your file using use and then call addDebug() method. This will print log message in var/log/debug.log file



                            use PsrLogLoggerInterface;

                            class demo {
                            function demo()
                            {
                            //EDIT: Using debug instead of addDebug for PSR compatiblity
                            $this->_objectManager->get('PsrLogLoggerInterface')->debug("your message goes here");
                            }

                            }





                            share|improve this answer





















                            • 2





                              you shouldn't ujse addDebug as that's not psr logger compatible. use just debug instead.

                              – Maciej Paprocki
                              Nov 9 '16 at 15:56














                            3












                            3








                            3







                            Include psr logger class in your file using use and then call addDebug() method. This will print log message in var/log/debug.log file



                            use PsrLogLoggerInterface;

                            class demo {
                            function demo()
                            {
                            //EDIT: Using debug instead of addDebug for PSR compatiblity
                            $this->_objectManager->get('PsrLogLoggerInterface')->debug("your message goes here");
                            }

                            }





                            share|improve this answer















                            Include psr logger class in your file using use and then call addDebug() method. This will print log message in var/log/debug.log file



                            use PsrLogLoggerInterface;

                            class demo {
                            function demo()
                            {
                            //EDIT: Using debug instead of addDebug for PSR compatiblity
                            $this->_objectManager->get('PsrLogLoggerInterface')->debug("your message goes here");
                            }

                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited May 11 '17 at 14:27









                            medmek

                            12616




                            12616










                            answered Dec 15 '15 at 11:26









                            chirag dodiachirag dodia

                            71731021




                            71731021








                            • 2





                              you shouldn't ujse addDebug as that's not psr logger compatible. use just debug instead.

                              – Maciej Paprocki
                              Nov 9 '16 at 15:56














                            • 2





                              you shouldn't ujse addDebug as that's not psr logger compatible. use just debug instead.

                              – Maciej Paprocki
                              Nov 9 '16 at 15:56








                            2




                            2





                            you shouldn't ujse addDebug as that's not psr logger compatible. use just debug instead.

                            – Maciej Paprocki
                            Nov 9 '16 at 15:56





                            you shouldn't ujse addDebug as that's not psr logger compatible. use just debug instead.

                            – Maciej Paprocki
                            Nov 9 '16 at 15:56











                            3














                            In a simple way if you don't want to create dependency injection or anything else use below code it will store log in system.log file



                            $logger = MagentoFrameworkAppObjectManager::getInstance()->get(PsrLogLoggerInterface::class);
                            $logger->info('message');


                            That's all..






                            share|improve this answer






























                              3














                              In a simple way if you don't want to create dependency injection or anything else use below code it will store log in system.log file



                              $logger = MagentoFrameworkAppObjectManager::getInstance()->get(PsrLogLoggerInterface::class);
                              $logger->info('message');


                              That's all..






                              share|improve this answer




























                                3












                                3








                                3







                                In a simple way if you don't want to create dependency injection or anything else use below code it will store log in system.log file



                                $logger = MagentoFrameworkAppObjectManager::getInstance()->get(PsrLogLoggerInterface::class);
                                $logger->info('message');


                                That's all..






                                share|improve this answer















                                In a simple way if you don't want to create dependency injection or anything else use below code it will store log in system.log file



                                $logger = MagentoFrameworkAppObjectManager::getInstance()->get(PsrLogLoggerInterface::class);
                                $logger->info('message');


                                That's all..







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited 2 days ago

























                                answered Oct 23 '18 at 9:54









                                HimanshuHimanshu

                                792521




                                792521























                                    2














                                    If you are looking for elegant custom log handler, I recommend you to create a helper (which able to use anywhere in your project by injecting it in your constructors).



                                    Inspired from answer of Petar Dzhambazov and halk, ladies and gentlement I introduced you a better and shorter way instead of duplicated custom log code all the time.




                                    StackoverflowCoreHelperData.php




                                    <?php
                                    /**
                                    * Copyright © 2016 Toan Nguyen <https://nntoan.github.io>. All rights reserved.
                                    * See COPYING.txt for license details.
                                    */

                                    namespace StackoverflowCoreHelper;

                                    use MagentoFrameworkAppHelperAbstractHelper;
                                    use MagentoFrameworkAppHelperContext;
                                    use MagentoFrameworkObjectManagerInterface;
                                    use MonologHandlerStreamHandler;
                                    use MonologLogger;

                                    /**
                                    * Stackoverflow Core Helper
                                    *
                                    * @package StackoverflowCoreHelper
                                    * @author Toan Nguyen <https://github.com/nntoan>
                                    */
                                    class Data extends AbstractHelper
                                    {
                                    /**
                                    * @var MagentoFrameworkObjectManagerInterface
                                    */
                                    protected $objectManager;
                                    /**
                                    * @var PsrLogLoggerInterface
                                    */
                                    protected $defaultLogger;
                                    /**
                                    * @var string
                                    */
                                    protected $channelName;
                                    /**
                                    * @var string
                                    */
                                    protected $logFile;

                                    /**
                                    * Data constructor.
                                    *
                                    * @param Context $context Context
                                    * @param ObjectManagerInterface $objectManager Object manager
                                    */
                                    public function __construct(
                                    Context $context,
                                    ObjectManagerInterface $objectManager
                                    ) {
                                    parent::__construct($context);
                                    $this->objectManager = $objectManager;
                                    $this->defaultLogger = $context->getLogger();
                                    $this->channelName = 'stackoverflow-default-channel';
                                    $this->logFile = BP . '/var/log/stackoverflow.log';
                                    }

                                    /**
                                    * Get default/custom logger instance
                                    *
                                    * @param string $type
                                    * @param string|null $channelName
                                    * @param string|null $logFile
                                    *
                                    * @return PsrLogLoggerInterface
                                    */
                                    public function getLogger($type = 'default', $channelName = null, $logFile = null)
                                    {
                                    switch ($type) {
                                    case 'custom':
                                    $logger = $this->getCustomLogger($channelName, $logFile);
                                    break;
                                    case 'default':
                                    default:
                                    $logger = $this->getDefaultLogger();
                                    break;
                                    }

                                    return $logger;
                                    }

                                    /**
                                    * Return default logger instance
                                    *
                                    * @return PsrLogLoggerInterface
                                    */
                                    private function getDefaultLogger()
                                    {
                                    return $this->defaultLogger;
                                    }

                                    /**
                                    * Create new logger instance with custom channel name
                                    * and log file name
                                    *
                                    * @param string|null $channelName
                                    * @param string|null $logFile
                                    *
                                    * @return MonologLogger
                                    */
                                    private function getCustomLogger($channelName = null, $logFile = null)
                                    {
                                    if (!empty($channelName) && !empty($logFile)) {
                                    $this->channelName = $channelName;
                                    $this->logFile = BP . $logFile;
                                    }

                                    /** @var MonologLogger $logger */
                                    $logger = $this->objectManager->create(Logger::class, [$this->channelName]);

                                    /** @var MonologHandlerStreamHandler $streamHandler */
                                    $streamHandler = $this->objectManager->create(StreamHandler::class, [$this->logFile]);
                                    $logger->pushHandler($streamHandler);

                                    return $logger;
                                    }
                                    }


                                    USAGE




                                    VendorSomethingModelDonaldTrump.php




                                    <?php
                                    /**
                                    * Copyright © 2016 Toan Nguyen <https://nntoan.github.io>. All rights reserved.
                                    * See COPYING.txt for license details.
                                    */

                                    namespace VendorSomethingModel;

                                    use StackoverflowCoreHelperData as SoHelper;

                                    /**
                                    * DonaldTrump business logic file
                                    *
                                    * @package VendorSomethingModel
                                    * @author Toan Nguyen <https://github.com/nntoan>
                                    */
                                    class DonaldTrump
                                    {
                                    /**
                                    * @var PsrLogLoggerInterface
                                    */
                                    private $logger;

                                    const LOG_CHANNEL_NAME = 'donald-trump';
                                    const LOG_FILEPATH = '/var/log/donald-trump/make-america-great-again.log';

                                    /**
                                    * DonaldTrump constructor.
                                    *
                                    * @param SoHelper $soHelper
                                    */
                                    public function __construct(
                                    SoHelper $soHelper
                                    ) {
                                    $this->logger = $soHelper->getLogger('custom', self::LOG_CHANNEL_NAME, self::LOG_FILEPATH);
                                    }

                                    /**
                                    * Test my custom log
                                    *
                                    * @return void
                                    */
                                    public function test()
                                    {
                                    $this->logger->error('MAKE AMERICA GREAT AGAIN !?');
                                    }
                                    }


                                    As you see, whenever test() method called, the string MAKE AMERICA GREAT AGAIN !? will be log as error into a custom file (create folder automatically if doesn't exist) in <magento_dir>/var/log/donald-trump/make-america-great-again.log



                                    In other model, e.g HillaryClinton you can create simple declare new custom log and so on...



                                    Hope this helps ;)






                                    share|improve this answer





















                                    • 1





                                      Is this code implementing PSI? (Political Statements Injection) :P

                                      – 7ochem
                                      May 12 '17 at 14:56











                                    • @7ochem Oh yes, it is :v

                                      – Toan Nguyen
                                      May 14 '17 at 6:23
















                                    2














                                    If you are looking for elegant custom log handler, I recommend you to create a helper (which able to use anywhere in your project by injecting it in your constructors).



                                    Inspired from answer of Petar Dzhambazov and halk, ladies and gentlement I introduced you a better and shorter way instead of duplicated custom log code all the time.




                                    StackoverflowCoreHelperData.php




                                    <?php
                                    /**
                                    * Copyright © 2016 Toan Nguyen <https://nntoan.github.io>. All rights reserved.
                                    * See COPYING.txt for license details.
                                    */

                                    namespace StackoverflowCoreHelper;

                                    use MagentoFrameworkAppHelperAbstractHelper;
                                    use MagentoFrameworkAppHelperContext;
                                    use MagentoFrameworkObjectManagerInterface;
                                    use MonologHandlerStreamHandler;
                                    use MonologLogger;

                                    /**
                                    * Stackoverflow Core Helper
                                    *
                                    * @package StackoverflowCoreHelper
                                    * @author Toan Nguyen <https://github.com/nntoan>
                                    */
                                    class Data extends AbstractHelper
                                    {
                                    /**
                                    * @var MagentoFrameworkObjectManagerInterface
                                    */
                                    protected $objectManager;
                                    /**
                                    * @var PsrLogLoggerInterface
                                    */
                                    protected $defaultLogger;
                                    /**
                                    * @var string
                                    */
                                    protected $channelName;
                                    /**
                                    * @var string
                                    */
                                    protected $logFile;

                                    /**
                                    * Data constructor.
                                    *
                                    * @param Context $context Context
                                    * @param ObjectManagerInterface $objectManager Object manager
                                    */
                                    public function __construct(
                                    Context $context,
                                    ObjectManagerInterface $objectManager
                                    ) {
                                    parent::__construct($context);
                                    $this->objectManager = $objectManager;
                                    $this->defaultLogger = $context->getLogger();
                                    $this->channelName = 'stackoverflow-default-channel';
                                    $this->logFile = BP . '/var/log/stackoverflow.log';
                                    }

                                    /**
                                    * Get default/custom logger instance
                                    *
                                    * @param string $type
                                    * @param string|null $channelName
                                    * @param string|null $logFile
                                    *
                                    * @return PsrLogLoggerInterface
                                    */
                                    public function getLogger($type = 'default', $channelName = null, $logFile = null)
                                    {
                                    switch ($type) {
                                    case 'custom':
                                    $logger = $this->getCustomLogger($channelName, $logFile);
                                    break;
                                    case 'default':
                                    default:
                                    $logger = $this->getDefaultLogger();
                                    break;
                                    }

                                    return $logger;
                                    }

                                    /**
                                    * Return default logger instance
                                    *
                                    * @return PsrLogLoggerInterface
                                    */
                                    private function getDefaultLogger()
                                    {
                                    return $this->defaultLogger;
                                    }

                                    /**
                                    * Create new logger instance with custom channel name
                                    * and log file name
                                    *
                                    * @param string|null $channelName
                                    * @param string|null $logFile
                                    *
                                    * @return MonologLogger
                                    */
                                    private function getCustomLogger($channelName = null, $logFile = null)
                                    {
                                    if (!empty($channelName) && !empty($logFile)) {
                                    $this->channelName = $channelName;
                                    $this->logFile = BP . $logFile;
                                    }

                                    /** @var MonologLogger $logger */
                                    $logger = $this->objectManager->create(Logger::class, [$this->channelName]);

                                    /** @var MonologHandlerStreamHandler $streamHandler */
                                    $streamHandler = $this->objectManager->create(StreamHandler::class, [$this->logFile]);
                                    $logger->pushHandler($streamHandler);

                                    return $logger;
                                    }
                                    }


                                    USAGE




                                    VendorSomethingModelDonaldTrump.php




                                    <?php
                                    /**
                                    * Copyright © 2016 Toan Nguyen <https://nntoan.github.io>. All rights reserved.
                                    * See COPYING.txt for license details.
                                    */

                                    namespace VendorSomethingModel;

                                    use StackoverflowCoreHelperData as SoHelper;

                                    /**
                                    * DonaldTrump business logic file
                                    *
                                    * @package VendorSomethingModel
                                    * @author Toan Nguyen <https://github.com/nntoan>
                                    */
                                    class DonaldTrump
                                    {
                                    /**
                                    * @var PsrLogLoggerInterface
                                    */
                                    private $logger;

                                    const LOG_CHANNEL_NAME = 'donald-trump';
                                    const LOG_FILEPATH = '/var/log/donald-trump/make-america-great-again.log';

                                    /**
                                    * DonaldTrump constructor.
                                    *
                                    * @param SoHelper $soHelper
                                    */
                                    public function __construct(
                                    SoHelper $soHelper
                                    ) {
                                    $this->logger = $soHelper->getLogger('custom', self::LOG_CHANNEL_NAME, self::LOG_FILEPATH);
                                    }

                                    /**
                                    * Test my custom log
                                    *
                                    * @return void
                                    */
                                    public function test()
                                    {
                                    $this->logger->error('MAKE AMERICA GREAT AGAIN !?');
                                    }
                                    }


                                    As you see, whenever test() method called, the string MAKE AMERICA GREAT AGAIN !? will be log as error into a custom file (create folder automatically if doesn't exist) in <magento_dir>/var/log/donald-trump/make-america-great-again.log



                                    In other model, e.g HillaryClinton you can create simple declare new custom log and so on...



                                    Hope this helps ;)






                                    share|improve this answer





















                                    • 1





                                      Is this code implementing PSI? (Political Statements Injection) :P

                                      – 7ochem
                                      May 12 '17 at 14:56











                                    • @7ochem Oh yes, it is :v

                                      – Toan Nguyen
                                      May 14 '17 at 6:23














                                    2












                                    2








                                    2







                                    If you are looking for elegant custom log handler, I recommend you to create a helper (which able to use anywhere in your project by injecting it in your constructors).



                                    Inspired from answer of Petar Dzhambazov and halk, ladies and gentlement I introduced you a better and shorter way instead of duplicated custom log code all the time.




                                    StackoverflowCoreHelperData.php




                                    <?php
                                    /**
                                    * Copyright © 2016 Toan Nguyen <https://nntoan.github.io>. All rights reserved.
                                    * See COPYING.txt for license details.
                                    */

                                    namespace StackoverflowCoreHelper;

                                    use MagentoFrameworkAppHelperAbstractHelper;
                                    use MagentoFrameworkAppHelperContext;
                                    use MagentoFrameworkObjectManagerInterface;
                                    use MonologHandlerStreamHandler;
                                    use MonologLogger;

                                    /**
                                    * Stackoverflow Core Helper
                                    *
                                    * @package StackoverflowCoreHelper
                                    * @author Toan Nguyen <https://github.com/nntoan>
                                    */
                                    class Data extends AbstractHelper
                                    {
                                    /**
                                    * @var MagentoFrameworkObjectManagerInterface
                                    */
                                    protected $objectManager;
                                    /**
                                    * @var PsrLogLoggerInterface
                                    */
                                    protected $defaultLogger;
                                    /**
                                    * @var string
                                    */
                                    protected $channelName;
                                    /**
                                    * @var string
                                    */
                                    protected $logFile;

                                    /**
                                    * Data constructor.
                                    *
                                    * @param Context $context Context
                                    * @param ObjectManagerInterface $objectManager Object manager
                                    */
                                    public function __construct(
                                    Context $context,
                                    ObjectManagerInterface $objectManager
                                    ) {
                                    parent::__construct($context);
                                    $this->objectManager = $objectManager;
                                    $this->defaultLogger = $context->getLogger();
                                    $this->channelName = 'stackoverflow-default-channel';
                                    $this->logFile = BP . '/var/log/stackoverflow.log';
                                    }

                                    /**
                                    * Get default/custom logger instance
                                    *
                                    * @param string $type
                                    * @param string|null $channelName
                                    * @param string|null $logFile
                                    *
                                    * @return PsrLogLoggerInterface
                                    */
                                    public function getLogger($type = 'default', $channelName = null, $logFile = null)
                                    {
                                    switch ($type) {
                                    case 'custom':
                                    $logger = $this->getCustomLogger($channelName, $logFile);
                                    break;
                                    case 'default':
                                    default:
                                    $logger = $this->getDefaultLogger();
                                    break;
                                    }

                                    return $logger;
                                    }

                                    /**
                                    * Return default logger instance
                                    *
                                    * @return PsrLogLoggerInterface
                                    */
                                    private function getDefaultLogger()
                                    {
                                    return $this->defaultLogger;
                                    }

                                    /**
                                    * Create new logger instance with custom channel name
                                    * and log file name
                                    *
                                    * @param string|null $channelName
                                    * @param string|null $logFile
                                    *
                                    * @return MonologLogger
                                    */
                                    private function getCustomLogger($channelName = null, $logFile = null)
                                    {
                                    if (!empty($channelName) && !empty($logFile)) {
                                    $this->channelName = $channelName;
                                    $this->logFile = BP . $logFile;
                                    }

                                    /** @var MonologLogger $logger */
                                    $logger = $this->objectManager->create(Logger::class, [$this->channelName]);

                                    /** @var MonologHandlerStreamHandler $streamHandler */
                                    $streamHandler = $this->objectManager->create(StreamHandler::class, [$this->logFile]);
                                    $logger->pushHandler($streamHandler);

                                    return $logger;
                                    }
                                    }


                                    USAGE




                                    VendorSomethingModelDonaldTrump.php




                                    <?php
                                    /**
                                    * Copyright © 2016 Toan Nguyen <https://nntoan.github.io>. All rights reserved.
                                    * See COPYING.txt for license details.
                                    */

                                    namespace VendorSomethingModel;

                                    use StackoverflowCoreHelperData as SoHelper;

                                    /**
                                    * DonaldTrump business logic file
                                    *
                                    * @package VendorSomethingModel
                                    * @author Toan Nguyen <https://github.com/nntoan>
                                    */
                                    class DonaldTrump
                                    {
                                    /**
                                    * @var PsrLogLoggerInterface
                                    */
                                    private $logger;

                                    const LOG_CHANNEL_NAME = 'donald-trump';
                                    const LOG_FILEPATH = '/var/log/donald-trump/make-america-great-again.log';

                                    /**
                                    * DonaldTrump constructor.
                                    *
                                    * @param SoHelper $soHelper
                                    */
                                    public function __construct(
                                    SoHelper $soHelper
                                    ) {
                                    $this->logger = $soHelper->getLogger('custom', self::LOG_CHANNEL_NAME, self::LOG_FILEPATH);
                                    }

                                    /**
                                    * Test my custom log
                                    *
                                    * @return void
                                    */
                                    public function test()
                                    {
                                    $this->logger->error('MAKE AMERICA GREAT AGAIN !?');
                                    }
                                    }


                                    As you see, whenever test() method called, the string MAKE AMERICA GREAT AGAIN !? will be log as error into a custom file (create folder automatically if doesn't exist) in <magento_dir>/var/log/donald-trump/make-america-great-again.log



                                    In other model, e.g HillaryClinton you can create simple declare new custom log and so on...



                                    Hope this helps ;)






                                    share|improve this answer















                                    If you are looking for elegant custom log handler, I recommend you to create a helper (which able to use anywhere in your project by injecting it in your constructors).



                                    Inspired from answer of Petar Dzhambazov and halk, ladies and gentlement I introduced you a better and shorter way instead of duplicated custom log code all the time.




                                    StackoverflowCoreHelperData.php




                                    <?php
                                    /**
                                    * Copyright © 2016 Toan Nguyen <https://nntoan.github.io>. All rights reserved.
                                    * See COPYING.txt for license details.
                                    */

                                    namespace StackoverflowCoreHelper;

                                    use MagentoFrameworkAppHelperAbstractHelper;
                                    use MagentoFrameworkAppHelperContext;
                                    use MagentoFrameworkObjectManagerInterface;
                                    use MonologHandlerStreamHandler;
                                    use MonologLogger;

                                    /**
                                    * Stackoverflow Core Helper
                                    *
                                    * @package StackoverflowCoreHelper
                                    * @author Toan Nguyen <https://github.com/nntoan>
                                    */
                                    class Data extends AbstractHelper
                                    {
                                    /**
                                    * @var MagentoFrameworkObjectManagerInterface
                                    */
                                    protected $objectManager;
                                    /**
                                    * @var PsrLogLoggerInterface
                                    */
                                    protected $defaultLogger;
                                    /**
                                    * @var string
                                    */
                                    protected $channelName;
                                    /**
                                    * @var string
                                    */
                                    protected $logFile;

                                    /**
                                    * Data constructor.
                                    *
                                    * @param Context $context Context
                                    * @param ObjectManagerInterface $objectManager Object manager
                                    */
                                    public function __construct(
                                    Context $context,
                                    ObjectManagerInterface $objectManager
                                    ) {
                                    parent::__construct($context);
                                    $this->objectManager = $objectManager;
                                    $this->defaultLogger = $context->getLogger();
                                    $this->channelName = 'stackoverflow-default-channel';
                                    $this->logFile = BP . '/var/log/stackoverflow.log';
                                    }

                                    /**
                                    * Get default/custom logger instance
                                    *
                                    * @param string $type
                                    * @param string|null $channelName
                                    * @param string|null $logFile
                                    *
                                    * @return PsrLogLoggerInterface
                                    */
                                    public function getLogger($type = 'default', $channelName = null, $logFile = null)
                                    {
                                    switch ($type) {
                                    case 'custom':
                                    $logger = $this->getCustomLogger($channelName, $logFile);
                                    break;
                                    case 'default':
                                    default:
                                    $logger = $this->getDefaultLogger();
                                    break;
                                    }

                                    return $logger;
                                    }

                                    /**
                                    * Return default logger instance
                                    *
                                    * @return PsrLogLoggerInterface
                                    */
                                    private function getDefaultLogger()
                                    {
                                    return $this->defaultLogger;
                                    }

                                    /**
                                    * Create new logger instance with custom channel name
                                    * and log file name
                                    *
                                    * @param string|null $channelName
                                    * @param string|null $logFile
                                    *
                                    * @return MonologLogger
                                    */
                                    private function getCustomLogger($channelName = null, $logFile = null)
                                    {
                                    if (!empty($channelName) && !empty($logFile)) {
                                    $this->channelName = $channelName;
                                    $this->logFile = BP . $logFile;
                                    }

                                    /** @var MonologLogger $logger */
                                    $logger = $this->objectManager->create(Logger::class, [$this->channelName]);

                                    /** @var MonologHandlerStreamHandler $streamHandler */
                                    $streamHandler = $this->objectManager->create(StreamHandler::class, [$this->logFile]);
                                    $logger->pushHandler($streamHandler);

                                    return $logger;
                                    }
                                    }


                                    USAGE




                                    VendorSomethingModelDonaldTrump.php




                                    <?php
                                    /**
                                    * Copyright © 2016 Toan Nguyen <https://nntoan.github.io>. All rights reserved.
                                    * See COPYING.txt for license details.
                                    */

                                    namespace VendorSomethingModel;

                                    use StackoverflowCoreHelperData as SoHelper;

                                    /**
                                    * DonaldTrump business logic file
                                    *
                                    * @package VendorSomethingModel
                                    * @author Toan Nguyen <https://github.com/nntoan>
                                    */
                                    class DonaldTrump
                                    {
                                    /**
                                    * @var PsrLogLoggerInterface
                                    */
                                    private $logger;

                                    const LOG_CHANNEL_NAME = 'donald-trump';
                                    const LOG_FILEPATH = '/var/log/donald-trump/make-america-great-again.log';

                                    /**
                                    * DonaldTrump constructor.
                                    *
                                    * @param SoHelper $soHelper
                                    */
                                    public function __construct(
                                    SoHelper $soHelper
                                    ) {
                                    $this->logger = $soHelper->getLogger('custom', self::LOG_CHANNEL_NAME, self::LOG_FILEPATH);
                                    }

                                    /**
                                    * Test my custom log
                                    *
                                    * @return void
                                    */
                                    public function test()
                                    {
                                    $this->logger->error('MAKE AMERICA GREAT AGAIN !?');
                                    }
                                    }


                                    As you see, whenever test() method called, the string MAKE AMERICA GREAT AGAIN !? will be log as error into a custom file (create folder automatically if doesn't exist) in <magento_dir>/var/log/donald-trump/make-america-great-again.log



                                    In other model, e.g HillaryClinton you can create simple declare new custom log and so on...



                                    Hope this helps ;)







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Apr 13 '17 at 12:54









                                    Community

                                    1




                                    1










                                    answered Nov 20 '16 at 14:59









                                    Toan NguyenToan Nguyen

                                    1,5721034




                                    1,5721034








                                    • 1





                                      Is this code implementing PSI? (Political Statements Injection) :P

                                      – 7ochem
                                      May 12 '17 at 14:56











                                    • @7ochem Oh yes, it is :v

                                      – Toan Nguyen
                                      May 14 '17 at 6:23














                                    • 1





                                      Is this code implementing PSI? (Political Statements Injection) :P

                                      – 7ochem
                                      May 12 '17 at 14:56











                                    • @7ochem Oh yes, it is :v

                                      – Toan Nguyen
                                      May 14 '17 at 6:23








                                    1




                                    1





                                    Is this code implementing PSI? (Political Statements Injection) :P

                                    – 7ochem
                                    May 12 '17 at 14:56





                                    Is this code implementing PSI? (Political Statements Injection) :P

                                    – 7ochem
                                    May 12 '17 at 14:56













                                    @7ochem Oh yes, it is :v

                                    – Toan Nguyen
                                    May 14 '17 at 6:23





                                    @7ochem Oh yes, it is :v

                                    – Toan Nguyen
                                    May 14 '17 at 6:23











                                    2














                                    There is one update for logger in 2.2. You can enable logger for production mode by run SQL:



                                     "INSERT INTO core_config_data (scope, scope_id, path, value) VALUES ('default', '0', 'dev/debug/debug_logging', '1');"


                                    Then you can use PsrLogLoggerInterface for print log just like above answers:



                                    protected $logger;

                                    public function __construct(
                                    PsrLogLoggerInterface $logger
                                    ) {
                                    $this->logger = $logger;
                                    }

                                    public function yourFunction() {
                                    $data = ["test" => "testing"];
                                    $this->logger->debug(var_export($data, true));
                                    }





                                    share|improve this answer
























                                    • thanks, and you can also use this instead of QUERY SQL: In the Magento admin panel, go to "Stores" -> "Configuration" -> "Advanced" -> "Developer" -> "Debug" -> "Log to File". Setting this to "Yes" will cause debug information to be logged to var/log/debug.log in your Magento application directory.

                                      – fudu
                                      Oct 31 '18 at 3:47
















                                    2














                                    There is one update for logger in 2.2. You can enable logger for production mode by run SQL:



                                     "INSERT INTO core_config_data (scope, scope_id, path, value) VALUES ('default', '0', 'dev/debug/debug_logging', '1');"


                                    Then you can use PsrLogLoggerInterface for print log just like above answers:



                                    protected $logger;

                                    public function __construct(
                                    PsrLogLoggerInterface $logger
                                    ) {
                                    $this->logger = $logger;
                                    }

                                    public function yourFunction() {
                                    $data = ["test" => "testing"];
                                    $this->logger->debug(var_export($data, true));
                                    }





                                    share|improve this answer
























                                    • thanks, and you can also use this instead of QUERY SQL: In the Magento admin panel, go to "Stores" -> "Configuration" -> "Advanced" -> "Developer" -> "Debug" -> "Log to File". Setting this to "Yes" will cause debug information to be logged to var/log/debug.log in your Magento application directory.

                                      – fudu
                                      Oct 31 '18 at 3:47














                                    2












                                    2








                                    2







                                    There is one update for logger in 2.2. You can enable logger for production mode by run SQL:



                                     "INSERT INTO core_config_data (scope, scope_id, path, value) VALUES ('default', '0', 'dev/debug/debug_logging', '1');"


                                    Then you can use PsrLogLoggerInterface for print log just like above answers:



                                    protected $logger;

                                    public function __construct(
                                    PsrLogLoggerInterface $logger
                                    ) {
                                    $this->logger = $logger;
                                    }

                                    public function yourFunction() {
                                    $data = ["test" => "testing"];
                                    $this->logger->debug(var_export($data, true));
                                    }





                                    share|improve this answer













                                    There is one update for logger in 2.2. You can enable logger for production mode by run SQL:



                                     "INSERT INTO core_config_data (scope, scope_id, path, value) VALUES ('default', '0', 'dev/debug/debug_logging', '1');"


                                    Then you can use PsrLogLoggerInterface for print log just like above answers:



                                    protected $logger;

                                    public function __construct(
                                    PsrLogLoggerInterface $logger
                                    ) {
                                    $this->logger = $logger;
                                    }

                                    public function yourFunction() {
                                    $data = ["test" => "testing"];
                                    $this->logger->debug(var_export($data, true));
                                    }






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Dec 1 '17 at 5:54









                                    Yogesh KarodiyaYogesh Karodiya

                                    1,89321235




                                    1,89321235













                                    • thanks, and you can also use this instead of QUERY SQL: In the Magento admin panel, go to "Stores" -> "Configuration" -> "Advanced" -> "Developer" -> "Debug" -> "Log to File". Setting this to "Yes" will cause debug information to be logged to var/log/debug.log in your Magento application directory.

                                      – fudu
                                      Oct 31 '18 at 3:47



















                                    • thanks, and you can also use this instead of QUERY SQL: In the Magento admin panel, go to "Stores" -> "Configuration" -> "Advanced" -> "Developer" -> "Debug" -> "Log to File". Setting this to "Yes" will cause debug information to be logged to var/log/debug.log in your Magento application directory.

                                      – fudu
                                      Oct 31 '18 at 3:47

















                                    thanks, and you can also use this instead of QUERY SQL: In the Magento admin panel, go to "Stores" -> "Configuration" -> "Advanced" -> "Developer" -> "Debug" -> "Log to File". Setting this to "Yes" will cause debug information to be logged to var/log/debug.log in your Magento application directory.

                                    – fudu
                                    Oct 31 '18 at 3:47





                                    thanks, and you can also use this instead of QUERY SQL: In the Magento admin panel, go to "Stores" -> "Configuration" -> "Advanced" -> "Developer" -> "Debug" -> "Log to File". Setting this to "Yes" will cause debug information to be logged to var/log/debug.log in your Magento application directory.

                                    – fudu
                                    Oct 31 '18 at 3:47











                                    1















                                    1. Inject $logger class in constructor PsrLogLoggerInterface $logger

                                      This is achieved by passing $logger as argument.



                                    2. Initialize $logger in constructor



                                      $this->logger = $logger



                                    3. In function within the class you want to log use the below line



                                      $this->logger->debug($message);
                                      $this->logger->log($level, $message);







                                    share|improve this answer






























                                      1















                                      1. Inject $logger class in constructor PsrLogLoggerInterface $logger

                                        This is achieved by passing $logger as argument.



                                      2. Initialize $logger in constructor



                                        $this->logger = $logger



                                      3. In function within the class you want to log use the below line



                                        $this->logger->debug($message);
                                        $this->logger->log($level, $message);







                                      share|improve this answer




























                                        1












                                        1








                                        1








                                        1. Inject $logger class in constructor PsrLogLoggerInterface $logger

                                          This is achieved by passing $logger as argument.



                                        2. Initialize $logger in constructor



                                          $this->logger = $logger



                                        3. In function within the class you want to log use the below line



                                          $this->logger->debug($message);
                                          $this->logger->log($level, $message);







                                        share|improve this answer
















                                        1. Inject $logger class in constructor PsrLogLoggerInterface $logger

                                          This is achieved by passing $logger as argument.



                                        2. Initialize $logger in constructor



                                          $this->logger = $logger



                                        3. In function within the class you want to log use the below line



                                          $this->logger->debug($message);
                                          $this->logger->log($level, $message);








                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Apr 3 '17 at 9:35









                                        7ochem

                                        5,72193668




                                        5,72193668










                                        answered Nov 20 '16 at 14:11









                                        oscprofessionalsoscprofessionals

                                        35917




                                        35917























                                            1














                                            If you need it within your single class with custom log file:



                                            public function __construct(PsrLogLoggerInterface $logger, MagentoFrameworkAppFilesystemDirectoryList $dir) 
                                            {
                                            $this->logger = $logger;
                                            $this->dir = $dir;

                                            $this->logger->pushHandler(new MonologHandlerStreamHandler($this->dir->getRoot().'/var/log/custom.log'));
                                            }





                                            share|improve this answer




























                                              1














                                              If you need it within your single class with custom log file:



                                              public function __construct(PsrLogLoggerInterface $logger, MagentoFrameworkAppFilesystemDirectoryList $dir) 
                                              {
                                              $this->logger = $logger;
                                              $this->dir = $dir;

                                              $this->logger->pushHandler(new MonologHandlerStreamHandler($this->dir->getRoot().'/var/log/custom.log'));
                                              }





                                              share|improve this answer


























                                                1












                                                1








                                                1







                                                If you need it within your single class with custom log file:



                                                public function __construct(PsrLogLoggerInterface $logger, MagentoFrameworkAppFilesystemDirectoryList $dir) 
                                                {
                                                $this->logger = $logger;
                                                $this->dir = $dir;

                                                $this->logger->pushHandler(new MonologHandlerStreamHandler($this->dir->getRoot().'/var/log/custom.log'));
                                                }





                                                share|improve this answer













                                                If you need it within your single class with custom log file:



                                                public function __construct(PsrLogLoggerInterface $logger, MagentoFrameworkAppFilesystemDirectoryList $dir) 
                                                {
                                                $this->logger = $logger;
                                                $this->dir = $dir;

                                                $this->logger->pushHandler(new MonologHandlerStreamHandler($this->dir->getRoot().'/var/log/custom.log'));
                                                }






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Aug 2 '17 at 6:58









                                                mshakeelmshakeel

                                                321410




                                                321410























                                                    0














                                                    Place PSR logger code in your constructor:



                                                    protected $logger;
                                                    public function __construct(PsrLogLoggerInterface $logger)
                                                    {
                                                    $this->logger = $logger;
                                                    }


                                                    then you can use in your function like:



                                                    $this->logger->info($message);





                                                    share|improve this answer




























                                                      0














                                                      Place PSR logger code in your constructor:



                                                      protected $logger;
                                                      public function __construct(PsrLogLoggerInterface $logger)
                                                      {
                                                      $this->logger = $logger;
                                                      }


                                                      then you can use in your function like:



                                                      $this->logger->info($message);





                                                      share|improve this answer


























                                                        0












                                                        0








                                                        0







                                                        Place PSR logger code in your constructor:



                                                        protected $logger;
                                                        public function __construct(PsrLogLoggerInterface $logger)
                                                        {
                                                        $this->logger = $logger;
                                                        }


                                                        then you can use in your function like:



                                                        $this->logger->info($message);





                                                        share|improve this answer













                                                        Place PSR logger code in your constructor:



                                                        protected $logger;
                                                        public function __construct(PsrLogLoggerInterface $logger)
                                                        {
                                                        $this->logger = $logger;
                                                        }


                                                        then you can use in your function like:



                                                        $this->logger->info($message);






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Jan 13 '17 at 7:31







                                                        user49289
























                                                            protected by Qaisar Satti Dec 15 '15 at 12:04



                                                            Thank you for your interest in this question.
                                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                            Would you like to answer one of these unanswered questions instead?



                                                            Popular posts from this blog

                                                            William S. Burroughs

                                                            Eda skans

                                                            What is the difference between apt, apt-get and git?