Magento 2 : Create custom logging


Magento 2 uses monolog library to log messages. You can check this library in following  path location in magento 2.


Log file will be created inside var/log folder

If you want to use log in your custom module, you need to add instance of  monolog class in your custom file class. You need to pass the instance in the constructor of your custom class.

Go to app/code/yourCompany/yourModule/Block/custom.php

add following protected variable  in custom file class.

* @var \Psr\Log\LoggerInterface
protected $_logger;

add following parameter in your custom class  __construct()

\Psr\Log\LoggerInterface $logger

Now, we need to create an object

$this->_logger = $logger;
$this->_logger->addDebug('some text or variable');

Finally, constructor function looks like following

public function __construct(
        \Magento\Framework\View\Element\Context $context,
        \Magento\Cms\Model\Page $page,
        \Magento\Cms\Model\Template\FilterProvider $filterProvider,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Cms\Model\PageFactory $pageFactory,
        \Magento\Framework\View\Page\Config $pageConfig,
        \Psr\Log\LoggerInterface $logger,
        array $data = []
    ) {
        parent::__construct($context, $data);
        // used singleton (instead factory) because there exist dependencies on \Magento\Cms\Helper\Page
        $this->_page = $page;
        $this->_filterProvider = $filterProvider;
        $this->_storeManager = $storeManager;
        $this->_pageFactory = $pageFactory;
        $this->pageConfig = $pageConfig;
        $this->_logger = $logger;
        $this->_logger->addDebug('some text or variable');

Here is the use of some predefined examples :

$this->_logger->addDebug($message); // log location: var/log/system.log
$this->_logger->addInfo($message); // log location: var/log/exception.log
$this->_logger->addNotice($message); // log location: var/log/exception.log
$this->_logger->addError($message); // log location: var/log/exception.log
$this->_logger->critical($e); // log location: var/log/exception.log
You can also write to the logs using the zend library
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
$logger = new \Zend\Log\Logger();
$logger->info('Your text message');

Magento : Fetch products with layered navigation programmatically in custom php file

 Buy cheap and genuine Windows 7 product key  |
 Windows 7 Product Key for Windows 32bit/64bit Updated 2016y  |
 Windows 7 Ultimate ISO download  |
 Windows 7 Product Key Generator 32 bit and 64 bit Full  |
 Legit Windows 7 Product Key Online Store, PayPal Support  |
 Windows 7 Ultimate with Service Pack 1 Product Key,Windows 7 Key Sale  |
 Windows 7 Key  |
 Get Free Windows 7 Product Key  |

Here is way to fetch products with layered navigation programmatically in custom php file.

require_once('app/Mage.php'); //Must have file to begin
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); //Initialize store
$catId = Mage::app()->getRequest()->getParam('categoryId'); //Pass categoryId in get variable
    $storeId = Mage::app()->getWebsite(true)->getDefaultGroup()->getDefaultStoreId();
    $page_no = Mage::app()->getRequest()->getParam('page_no');
    $params = Mage::app()->getRequest()->getParams(); //Pass attributes in key=>value form to filter results.
    $category = Mage::getModel('catalog/category')->load($catId);
    $layer = Mage::getModel("catalog/layer");
    $attributes = $layer->getFilterableAttributes(); //get all filterable attributes available in selected category layered navigation
    $attr = array();
    foreach ($attributes as $attribute) {
        if ($attribute->getAttributeCode() == 'price') {
            $filterBlockName = 'catalog/layer_filter_price';
        } elseif ($attribute->getBackendType() == 'decimal') {
            $filterBlockName = 'catalog/layer_filter_decimal';
        } else {
            $filterBlockName = 'catalog/layer_filter_attribute';
        $attr[$attribute->getAttributeCode()] = $attribute->getFrontendLabel();
    $filters = array_intersect_key($params, $attr);
    $collection = $category->getProductCollection()
                        'status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
    foreach ($filters as $key => $value) {
        if($key == 'price'){
            $priceFilter = explode('-', $value);
            $collection->addAttributeToFilter('price', array('gteq' => $priceFilter[0]));
            $collection->addAttributeToFilter('price', array('lteq' => $priceFilter[1]));
            $collection->addAttributeToFilter($key, array('in' => $value));
    $collection->setPage($page_no, 10);
foreach($collection as $product){
   echo $product->getName();

add custom role

The key features of WordPress that is often overlooked is that there are a number of different user roles available. These user roles can  help make insure that only the people have access to just the areas they need and also helps minimize the chances of any  accidents happening that could potentially bring down the site. in this article we will look at those user roles briefly and also go into how to create your own custom roles.

User roles have been an important part of the WordPress experience since version 2.0. Most people don’t even know they exist and assign administrator rights to everyone who has access to their site dashboard (obviously not a good thing for a whole bunch of reasons). Off the shelf, WordPress comes with six default user roles:

Administrator: someone who has access to all the administrative features and functions within a site.
Editor: someone who can publish and manage posts of all users, including their own.
Author: someone who can publish and manage their own posts.
Contributor: someone who can write and manage their own posts but can’t publish them.
Subscriber: someone who can only manage their profile.

Why Use Custom User Roles?

The most part the default user roles are all that are needed. But there are cases where you need a user role that doesn’t fit in with the parameters of the default roles. And in this article We’ll see how to create custom user roles without using a plugin.

Lets thought on why we want to use Custom User roles. Typically use Custom User roles to make sure that clients only have access to what they need.

But if you are responsible for making sure the site stays up 24/7, then We recommend restricting the access of the client through a custom user role. That way We can give the client everything they need to make their site effective, like add content, maybe add events whatever they need to do. What they can’t do is things that can bring the site down or mess-up some functionality. We restrict things like access to add or remove plugins, themes, update core, all the kinds of things We’d want to do as part of my ongoing maintenance.

But lets start with a quick review of the basics, shall we?

Basic WordPress Functions

In order to manage roles and capabilities effectively, there are five very straightforward functions:

add_role(): Enables you to add a custom role.
remove_role(): Enables you to remove a custom role.
add_cap(): Enables you to add a custom capability to a role.
remove_cap(): Enables you to remove a custom capability from a role.
get_role (): Gets information about a role as well as the capabilities associated with the role.

We are only going to use the add_role() function for this article as we are going to create a custom user role for our fictitious client.

Defining The User Role

So before we dive into the code we need to have a plan, because diving into code without a plan is never a good idea.

So we need to give the user role a name. We’ll keep it simple and call the user role ‘Customer’.

So what can the user role ‘Customer’ actually do? There are over 50 different capabilities available in a clean install of WordPress (the number increases once you start adding plugins, but we’ll go over that in another article). For our purposes we want the client to be able to do the following:

Create posts
Edit posts
Edit Others posts
Manage categories
Edit Pages

Equally important is what we don’t want them to be able to do:

Edit themes
Add or Remove Plugins
Update core

Writing the Code

We are going to put this code into the functions.php file for our active theme. So lets start by adding this to the file:

// Add a custom user role

$result = add_role( 'customer', __(
'Customer' ),
array( ) );

By adding that piece of code, you have technically created a new user role (you can check it in the drop down on the Add New User page and it should be there). The problem is this user role has no functionality assigned to it. So the next step is obviously to add the functionality we had previously identified in our requirements above. Just add the array code to what you have already entered into your functions.php file.

// Add a custom user role

$result = add_role( 'customer', __(

'Customer' ),


'read' => true, // true allows this capability
'edit_posts' => true, // Allows user to edit their own posts
'edit_pages' => true, // Allows user to edit pages
'edit_others_posts' => true, // Allows user to edit others posts not just their own
'create_posts' => true, // Allows user to create new posts
'manage_categories' => true, // Allows user to manage post categories
'publish_posts' => true, // Allows the user to publish, otherwise posts stays in draft mode



That will give us the functionality we want the client to have but we still need to restrict them from doing things that could potentially cripple the site. So lets add that now.

// Add a custom user role

$result = add_role( 'customer', __(

'Customer' ),


'read' => true, // true allows this capability
'edit_posts' => true, // Allows user to edit their own posts
'edit_pages' => true, // Allows user to edit pages
'edit_others_posts' => true, // Allows user to edit others posts not just their own
'create_posts' => true, // Allows user to create new posts
'manage_categories' => true, // Allows user to manage post categories
'publish_posts' => true, // Allows the user to publish, otherwise posts stays in draft mode
'edit_themes' => false, // false denies this capability. User can’t edit your theme
'install_plugins' => false, // User cant add new plugins
'update_plugin' => false, // User can’t update any plugins
'update_core' => false // user cant perform core updates

User Role Is Set Up Properly?

WordPress Sidebar Making sure your new user role is working as intended requires you to set up a new user with the appropriate role, log out and log back in as the new user.

Depending on what capabilities you’ve allowed and what you have denied, the first thing you should notice is a change in what’s available in the dashboard. The image below shows you what you would see if you set up the client role as we did above.

Magento2: Module File Structure

Magento 2 Module File structure

In Magento2, there are lots of differences you will find out, due to security purposes. Magento2 looks for the files that make up a module, including configuration files, in particular places inside the module file structure. Follow the predefined file structure to ensure that your module works as expected.

A module can live or can be place now anywhere in Magento root directory. Regardless of where you add it, you must be registered, for Registering your module we need to implement registeration.php file.

A typical file structure for a Magento 2 module:




































Main Directories

The main directories are:

  • Block — it contains PHP classes as part of MVC vertical implementation of module logic.
  • Controller — it contains PHP classes as part of MVC vertical implementation of module logic.
  • Helper — it contains PHP classes as part of MVC vertical implementation of module logic.
  • Model — it contains PHP classes as part of MVC vertical implementation of module logic.
  • Setup — it contains classes for module database structure and data setup which are invoked when installing or upgrading.

Additional directories

Additionally, there are folders for configuration and other ancillary functions for items like plug-ins, internationalization, and front-end layout files.

  • Api— it contains any PHP classes exposed to the API.
  • etc — it contains configuration files.
  • i18n — it contains localization different files, like language files.
  • Plugin — it contains any needed plugin files.
  • view — it contains non-object-oriented and non-static view level parts of the module such as design templates, email templates, and layout files.

Magento2: Registration of module

For Registering our custom module, we need to create a php file named registration.php in the root of our custom folder and write the below given code


if examine this code then you will see that after the name of module there is a __DIR__ variable which is a php variable to identify the current working directory, it means that you can register your module from any where in Root of magento directory.

Enjoy this Article, don’t miss to comment us or write us if you need to know more about magento2

Magento API, use in Android, Iphone, Windows Phone

There are two types of API to use in Magento –



The Magento SOAP API provides ability to manage eCommerce stores by providing calls for working with resources such as customers, categories, products, and sales orders. It also allows to manage shopping carts and inventory.


where yourmagentohost is the domain for your Magento host.

The following PHP example shows you how to make SOAP calls to the Magento API:

$client = new SoapClient('http://yourmagentohost/soap/api/?wsdl');

// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUserName', 'apiKey');

$result = $client->call($session, 'stuff.method');
$result = $client->call($session, 'stuff.method', 'arg1');
$result = $client->call($session, 'stuff.method', array('arg1', 'arg2', 'arg3'));
$result = $client->multiCall($session, array(
     array('stuff.method', 'arg1'),
     array('stuff.method', array('arg1', 'arg2'))

// If you don't need the session anymore