PHP code example of swf / slf4php

1. Go to this page and download the library: Download swf/slf4php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

swf / slf4php example snippets



use swf\slf4php\LoggerFactory;
use swf\slf4php\config\builder\LogConfigBuilder;
use swf\util\JsonUtil;

....

// you might use variables in the json file (unix like style) and we can pass an array to the json parsing mechanism
// to let it resolve the vars
$envVars = [
	'LOG_DIR' => '/var/log'
];
$loggerConfig = LogConfigBuilder::create()->initFromJson(JsonUtil::getJsonObjects("log.config.json"), $envVars)->build();
// and now we can init the factory
LoggerFactory::init($loggerConfig);

$myLogger = LoggerFactory::getLogger(YourClass::class);   // the parameter is the fully qualified class name of YourClass
$myLogger->info("This is a log message", []);

$logger = LoggerFactory::getLogger('\your\namespace\A\MyClass');

$logger = LoggerFactory::getLogger('JustAClass');

// this might be a huge object:
$jsonObj = json_decode($jsonString);
...
// and this is a bad idea...:
$myLogger->debug("Parsed json object is: " . print_r($jsonObj, true), []);

// this might be a huge object:
$jsonObj = json_decode($jsonString);
...
// do it this way instead:
$myLogger->debug("Parsed json object is: {}", [], $jsonObj);

$jsonObj = json_decode($jsonString);
...
// you shouldn't do string transformations like this
$myLogger->debug("Parsed json object is: {}", [], print_r($jsonObj, true));



namespace your\namespace;

use swf\slf4php\LoggerFactory;

class ClassA {

	protected static $_LOG;

	/**
	 * @return \swf\slf4php\Logger
	 */
	protected static function logger() {
		if (is_null(static::$_LOG))
			static::$_LOG = LoggerFactory::getLogger(static::class);
		return static::$_LOG;
	}

	public function logSomething() {
		self::logger()->info("a simple message...", []);
	}
}



// this can be on different namespace of course.. but this doesn't matter
namespace different\namespace;

use swf\slf4php\LoggerFactory;
use your\namespace\ClassA;

class ClassASubclass extends ClassA {

	// we need to override this! if we would not do this then we would inherit OR hijack the Logger instance
	// of our superclass...
	protected static $_LOG;

	public function anotherLog() {
		self::logger()->info("another message...", []);
	}
}