humanemulator.net — справка. Продукт, демо и покупка — на хуманэмулятор.рф | Демо | Купить | API | Changelog

addLogToSQLite

addLogToSQLite($logLevelCode,$message,$dataString,$caller); - if (!LogLevel::tryFrom($logLevelCode))

throw new InvalidArgumentException("Invalid log level code: $logLevelCode");
$logLevelName = LogLevel::getName($logLevelCode);
// Get LogLevel title
$loglevelTitle = match ($this->localizationCode) {
'ru' => $this->logLevelNameLocDictionaryRu[$logLevelName],
'tr' => $this->logLevelNameLocDictionaryTr[$logLevelName],
default => $logLevelName,
};
/** DateTime now formatted */
$dateTimeFormattedString = date($this->dateTimeFormat);
/** Is warning message */
$isWarningText = $logLevelCode === LogLevel::WARNING;
/** Is error or critical message? */
$isErrorText = $logLevelCode === LogLevel::ERROR
// Check error message on text
if (!$isErrorText) {
$messageToLower = mb_strtolower($message);
if (mb_strpos($messageToLower, 'error') !== false)
$isErrorText = true;
else if (mb_strpos($messageToLower, "ошибка") !== false)
$isErrorText = true;
else if (mb_strpos($messageToLower, "hata") !== false)
$isErrorText = true;
}
/** Is debug message? */
$isDebugText = $logLevelCode === LogLevel::DEBUG;
// Log file extension
$logFileExt = pathinfo($this->logFilePath, PATHINFO_EXTENSION);
// Многострочная лог строка?
$hasNewLinesFlag = false;
if (preg_match('/\R/', $message) === 1)
$hasNewLinesFlag = true;
/** Text to log */
$text = '';
if ($logFileExt === "html") {
$text = htmlspecialchars($message, ENT_QUOTES
if ($hasNewLinesFlag)
$text = '<pre>' . $text . "</pre>\n";
$text = $text . '<pre>' . $dataString . "</pre>";
} else {
$text = $message . ' ' . $dataString;
}
$text = "[$dateTimeFormattedString][$loglevelTitle][$caller] $text";
if ($logFileExt === "html") {
// Set text bold
$text = $this->setFormatTagsForHtmlFormat($text, $isBold, $isErrorText, $isDebugText, $isWarningText);
// Set paragraph
$text = '<p>' . $text . '</p>';
}
$text = $text . PHP_EOL;
// Create dir if not exists
$logFolderPath = dirname($this->logFilePath);
if (!is_dir($logFolderPath)) {
mkdir($logFolderPath, 0755, true);
}
// append line
$stream = fopen($this->logFilePath, 'a');
$result = fwrite($stream, $text);
fclose($stream);
// Append text to file
return $result;
}
/**
Append log message to SQL Light DB

Функция на вход принимает параметры:

  • $logLevelCode – Log level title
  • $message – Log message
  • $dataString – Data object string
  • $caller – Caller name

    После выполнения функции возвращаемое значение будет равно одному из двух :
  • true – успешно
  • false – не удалось

    Пример использования
    # Additional paths
    import sys
    sys.path.insert(0, '../../../Templates PY/')
    
    xhe_host = "127.0.0.1:7019"
    from xweb_human_emulator import *
    
    # start
    echo("<hr><font color=blue>logger.addLogToSQLite</font><hr>")
    
    echo("Initializing logger using SQLite for log storage: ")
    if logger.init(logSQLiteDbFilePath=debug.get_cur_script_folder() + "/logs/logger.db"):
    	echo("вњ“ Success\n\n")
    else:
    	echo("вњ— Failed\n\n")
    
    # 1
    echo("1. Adding trace entry to SQLite: ")
    if logger.addLogToSQLite(0, "Manual trace log", '{"key": "value"}', "ManualTest"):
    	echo("вњ“ Success\n\n")
    else:
    	echo("вњ— Failed\n\n")
    
    # 2
    echo("2. Adding info entry to SQLite: ")
    if logger.addLogToSQLite(2, "Manual info log", '{"status": "ok"}', "ManualTest"):
    	echo("вњ“ Success\n\n")
    else:
    	echo("вњ— Failed\n\n")
    
    # 3
    echo("3. Adding error entry to SQLite with empty data: ")
    if logger.addLogToSQLite(4, "Manual error log", "", "ManualTest"):
    	echo("вњ“ Success\n\n")
    else:
    	echo("вњ— Failed\n\n")
    
    # end
    echo("\n")
    
    app.quit()
    #region using
    
    using System;
    using System.Diagnostics;
    using System.Collections.Generic;
    using System.Linq;
    using System.IO;
    using System.Text;
    using System.Threading;
    
    using XHE;
    using XHE.XHE_DOM;
    using XHE.XHE_System;
    using XHE.XHE_Window;
    using XHE.XHE_Web;
    
    #endregion
    
    class Program:XHEScript
    {
    	static void Main(string[] args)
    	{
    		server = Environment.GetEnvironmentVariable("RPABOT_HOST_URL");
    		InitXHE();
    
    		echo("<hr><font color=blue>logger.addLogToSQLite</font><hr>");
    
    		echo("0. Initialize logger: ");
    		bool initResult = logger.init(0, true, true, "", "test\\logger_test.db");
    		if(initResult)
    			echo("вњ“ Init successful<br>");
    		else
    			echo("вњ— Init failed<br>");
    
    		// 1 step
    		echo("\n1. Add trace log entry to SQLite: ");
    		bool result1 = logger.addLogToSQLite(0, "Trace log entry", "{\"key\":\"value\"}", "TestCaller");
    		if(result1)
    			echo("вњ“ Trace log added successfully<br>");
    		else
    			echo("вњ— Failed to add trace log<br>");
    
    		// 2 step
    		echo("\n2. Add error log entry to SQLite: ");
    		bool result2 = logger.addLogToSQLite(4, "Error occurred", "{\"error\":\"connection failed\"}", "NetworkHandler");
    		if(result2)
    			echo("вњ“ Error log added successfully<br>");
    		else
    			echo("вњ— Failed to add error log<br>");
    
    		// 3 step
    		echo("\n3. Add info log with data string: ");
    		bool result3 = logger.addLogToSQLite(2, "Info message", "{\"status\":\"ok\",\"count\":42}", "DataManager");
    		if(result3)
    			echo("вњ“ Info log added successfully<br>");
    		else
    			echo("вњ— Failed to add info log<br>");
    
    		// 4 step
    		echo("\n4. Add warning log with caller: ");
    		bool result4 = logger.addLogToSQLite(3, "Warning: retry limit exceeded", "{\"retries\":5}", "APIClient");
    		if(result4)
    			echo("вњ“ Warning log added successfully<br>");
    		else
    			echo("вњ— Failed to add warning log<br>");
    
    		echo("\n\n");
    
    		app.quit();
    	}
    }
    const xhe_host = "127.0.0.1:7019";
    require("../../../Templates JS/init.js");
    const path = require("path");
    
    async function main()
    {
    	var dbPath = path.join(__dirname, "/logs/test_logger.db");
    	logger.init(1, true, true, "", dbPath, "d-m-Y H:i:s", "en", false, true);
    	
    	var result = logger.addLogToSQLite(0, "Trace message to SQLite", "{}", "TestCaller1");
    	if (result === true)
    		console.log("вњ“ Test 1: Add trace log to SQLite - PASSED");
    	else
    		console.log("вњ— Test 1: Add trace log to SQLite - FAILED");
    	
    	result = logger.addLogToSQLite(1, "Debug message to SQLite", "{\"key\":\"value\"}", "TestCaller2");
    	if (result === true)
    		console.log("вњ“ Test 2: Add debug log to SQLite - PASSED");
    	else
    		console.log("вњ— Test 2: Add debug log to SQLite - FAILED");
    	
    	result = logger.addLogToSQLite(2, "Info message to SQLite", "{\"status\":\"ok\"}", "TestCaller3");
    	if (result === true)
    		console.log("вњ“ Test 3: Add info log to SQLite - PASSED");
    	else
    		console.log("вњ— Test 3: Add info log to SQLite - FAILED");
    	
    	result = logger.addLogToSQLite(3, "Warning message to SQLite", "{\"warning\":\"test\"}", "TestCaller4");
    	if (result === true)
    		console.log("вњ“ Test 4: Add warning log to SQLite - PASSED");
    	else
    		console.log("вњ— Test 4: Add warning log to SQLite - FAILED");
    }
    
    main();

    =============================================
    logger    Объекты    DOM  System  Vision  Web  Window        
    =============================================
    если что-то непонятно или необходимо узнать или считаете что надо добавить по работе этой функции, пишите в комментарии или на наш форум
    .