ZetCode

PHP openlog 函数

最后修改于 2025 年 4 月 4 日

PHP 的 openlog 函数初始化与系统日志记录器的连接。它与 syslogcloselog 一起用于系统日志记录。

基本定义

openlog 为 PHP 准备好向系统日志记录器发送消息。它在发送消息之前配置日志记录的标识和选项。

语法:openlog(string $prefix, int $options, int $facility): bool。成功返回 true,失败返回 false。适用于类 Unix 系统。

基本系统日志记录

此示例演示了 openlog 最基本用法。

basic_logging.php
<?php

declare(strict_types=1);

openlog("MyPHPApp", LOG_PID | LOG_PERROR, LOG_USER);
syslog(LOG_INFO, "This is a test message");
closelog();

这会以标识符“MyPHPApp”打开与系统日志记录器的连接。消息将以进程 ID (LOG_PID) 出现在系统日志中,并且还会打印到 stderr (LOG_PERROR)。

不同的日志设备

这展示了如何为各种目的使用不同的日志设备。

facility_logging.php
<?php

declare(strict_types=1);

// Mail system logging
openlog("MailProcessor", LOG_PID, LOG_MAIL);
syslog(LOG_WARNING, "Failed to deliver email");
closelog();

// Security logging
openlog("AuthSystem", LOG_PID, LOG_AUTH);
syslog(LOG_ALERT, "Unauthorized access attempt");
closelog();

不同的设备会为不同的系统组件对日志进行分类。LOG_MAIL 用于邮件系统消息,而 LOG_AUTH 用于安全/授权。

使用不同选项进行日志记录

此示例演示了 openlog 提供的各种日志记录选项。

options_logging.php
<?php

declare(strict_types=1);

// Log to console immediately (LOG_CONS)
openlog("ConsoleApp", LOG_CONS, LOG_USER);
syslog(LOG_ERR, "Critical error occurred");
closelog();

// Delay opening until first message (LOG_NDELAY)
openlog("BackgroundApp", LOG_NDELAY, LOG_DAEMON);
syslog(LOG_INFO, "Background process started");
closelog();

如果 syslog 失败,LOG_CONS 会直接写入系统控制台。LOG_NDELAY 会立即打开连接,而不是等待第一条消息。

带有日志记录的错误处理

这展示了如何使用系统日志记录来实现错误处理。

error_logging.php
<?php

declare(strict_types=1);

function logError(string $message, int $severity = LOG_ERR): bool {
    if (!openlog("ErrorTracker", LOG_PID, LOG_LOCAL0)) {
        return false;
    }
    
    $result = syslog($severity, $message);
    closelog();
    return $result;
}

logError("Database connection failed", LOG_CRIT);

这会将日志记录封装在一个带有错误检查的函数中。如果 openlog 失败,它将返回 false。可以在调用函数时自定义严重性级别。

自定义日志类

此示例演示了一个使用 openlog 的简单日志类。

logger_class.php
<?php

declare(strict_types=1);

class SystemLogger {
    private string $ident;
    private int $options;
    private int $facility;
    
    public function __construct(string $ident, int $options, int $facility) {
        $this->ident = $ident;
        $this->options = $options;
        $this->facility = $facility;
    }
    
    public function log(string $message, int $priority): bool {
        if (!openlog($this->ident, $this->options, $this->facility)) {
            return false;
        }
        $result = syslog($priority, $message);
        closelog();
        return $result;
    }
}

$logger = new SystemLogger("MyApp", LOG_PID, LOG_USER);
$logger->log("Application initialized", LOG_INFO);

此类封装了日志记录功能以供重用。构造函数设置日志记录配置,log 方法处理消息发送。

最佳实践

来源

PHP openlog 文档

本教程通过各种场景下的系统日志记录的实际示例,涵盖了 PHP openlog 函数。

作者

我叫 Jan Bodnar,是一名热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 PHP 教程