Skip to content

Commit c9434e8

Browse files
authored
Create FileRouteWithPid.php
1 parent c43f011 commit c9434e8

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

src/route/FileRouteWithPid.php

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the smalex86\logger package.
5+
*
6+
* (c) Alexandr Smirnov <mail_er@mail.ru>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace smalex86\logger\route;
13+
14+
use smalex86\logger\route\FileRoute;
15+
16+
/**
17+
* Class for file logging of information with pid info into msg line
18+
* @author Alexandr Smirnov <mail_er@mail.ru>
19+
*/
20+
class FileRouteWithPid extends FileRoute {
21+
22+
/**
23+
* Message template with pid
24+
* @var string
25+
*/
26+
public $template = '{date} :: {pid} :: {level} :: {file}=>{line} :: {message} {context}';
27+
28+
/**
29+
* Method for suitable with PsrLogger.
30+
* Logs with an arbitrary level.
31+
*
32+
* @param mixed $level
33+
* @param string $message
34+
* @param array $context
35+
* @return bool
36+
*/
37+
public function log($level, $message, array $context = []): bool
38+
{
39+
// if level set in psrloglevel string
40+
if (is_string($level)) {
41+
$level = $this->getLogLevelFromRsrLogLevel($level);
42+
}
43+
// check for requirement of writing
44+
// it is determined by log maxLevel and msg level
45+
if ($this->maxLevel < $level) {
46+
return false;
47+
}
48+
// define msg status word
49+
$msgStatusWord = $this->getStatusWord($level);
50+
51+
// folder existing check and creating
52+
if (!file_exists($this->folder)) {
53+
mkdir($this->folder);
54+
}
55+
56+
// pull file and line
57+
$fileLine = $this->getFileLine();
58+
59+
// put message to log file
60+
return file_put_contents(
61+
realpath($this->folder) . DIRECTORY_SEPARATOR . $this->logFile,
62+
trim(strtr($this->template, [
63+
'{date}' => $this->getDate(),
64+
'{pid}' => getmypid(),
65+
'{level}' => $msgStatusWord,
66+
'{file}' => $fileLine['file'],
67+
'{line}' => $fileLine['line'],
68+
'{message}' => $message,
69+
'{context}' => $this->contextStringify($context),
70+
])) . PHP_EOL,
71+
FILE_APPEND);
72+
}
73+
74+
}

0 commit comments

Comments
 (0)