How to create a directory in Magento 2 Programmatically?

How to create a new Folder or Directory Magento 2?
When you are working for a custom module in Magento 2 and need to add the log to the custom file inside the var/log folder.

Log folder contains the multiple log files and if you want to create a new folder for your custom log of the module, You can create a New Folder programmatically using WriteInterface.

A simple demo to create a new folder or directory under the var/log section called Payment, We are adding our custom module log inside the payment folder, We first create a new Payment folder,

<?php
namespace Jesadiya\Directory\Model;

use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem\Directory\WriteInterface;

class CreateDirectory
{
    /**
     * @var Filesystem
     */
    protected $file;

    /**
     * @var WriteInterface
     */
    protected $newDirectory;

    public function __construct(
        Filesystem $file
    ) {
        $this->newDirectory = $file->getDirectoryWrite(DirectoryList::VAR_DIR);
    }

    /**
     * Create new folder
     *
     * @return bool
     * @throws LocalizedException
     */
    public function createDirectory()
    {
        $logPath = "log/payment";
        $newDirectory = false;
        try {
            $newDirectory = $this->newDirectory->create($logPath);
        } catch (FileSystemException $e) {
            throw new LocalizedException(
                __('We can\'t create directory "%1"', $logPath)
            );
        }

        return $newDirectory;
    }
}

The new Payment module will be generated after calling the createDirectory() method.

If the payment folder doesn’t exists create a new folder and return true If any issue occurred result will be false.