SeasLog PHP Extension

repository·master·Indexed 22 days ago

https://github.com/seasx/seaslog

A high-performance, PSR-3 compliant PHP extension for logging designed as a fast alternative to built-in functions and heavy third-party libraries. It features memory buffering, customizable log templates, performance tracing for function execution, and support for multiple appenders including File, TCP, and UDP. It includes a built-in analyzer for log counting and detail retrieval, as well as a framework for configuring healthy warning alerts via SMTP.

Tokens
10.7K
Snippets
27
Records
39
Agent score
77%

What's inside SeasLog

  1. Overview of SeasLog

    master

    SeasLog is an effective, fast, and stable logging extension for PHP. It is designed to provide a high-performance alternative to libraries like log4php while addressing the limitations of PHP's built-in error_log and syslog functions.

    Key Features:

    • Standardized Logging: Follows the PSR-3 logger interface specification.
    • High Performance: Optimized for high-concurrency environments.
    • Automated Error/Exception Tracking: Automatically records error and exception information.
    • Flexible Output: Supports configurable log directories and modules, and can send logs via TCP or UDP in RFC5424 format.
    • Request Tracking: Supports RequestId to distinguish between different requests.
    • Customization: Supports custom log templates and provides a framework for log analysis and alerting.
  2. Customize Log Templates with Variables

    master

    You can customize the log output format using the seaslog.default_template setting in seaslog.ini. The default template is %T | %L | %P | %Q | %t | %M.

    Available Template Variables

    VariableDescription
    %LLog Level
    %MLog Message
    %TDateTime (formatted by seaslog.default_datetime_format)
    %tTimestamp (milliseconds precision)
    %QRequestId (unique ID per request)
    %HHostName
    %PProcessId
    %DDomain:Port (or cli in CLI mode)
    %RRequest URI (or index script in CLI)
    %mRequest Method (or command script in CLI)
    %IClient IP (Priority: HTTP_X_REAL_IP > HTTP_X_FORWARDED_FOR > REMOTE_ADDR)
    %FFileName:LineNo
    %UMemory Usage (bytes)
    %uPeak Memory Usage (bytes)
    %CClass::Action (or function name)
    %BBasePath

    Example

    To change the format to [DateTime]:Level PID RequestId Timestamp Message, use:

    seaslog.default_template = "[%T]:%L %P %Q %t %M"
    seaslog.default_template = "[%T]:%L %P %Q %t %M"
  3. Standardize log directory structures

    master

    To maintain organized logs, follow these directory naming conventions:

    1. Root Directory: The log root directory must be determined via component configuration. Do not hardcode the root directory path in your application code.
    2. Subdirectories: Use the Logger to define specific subdirectories for different application logic layers. It is recommended that each Logger represents a specific logic layer and is assigned its own subdirectory under the root.

    Example Structure:

    • Root: /data/logs/tsb/
    • User Logic: /data/logs/tsb/user
    • Mobile Logic: /data/logs/tsb/mobile
  4. Understand SeasLog Log File Structure

    master

    Log files are organized by basePath / logger / {date}.log. The filename format is YYYYMMDD.log.

    Log File Splitting (disting_type)

    The file structure depends on the seaslog.disting_type configuration:

    • Type 0 (Default): All logs are combined into one file: basePath / logger / YYYYMMDD.log.
    • Type 1: Logs are split by severity:
      • basePath / logger / YYYYMMDD.INFO.log
      • basePath / logger / YYYYMMDD.WARNING.log
      • basePath / logger / YYYYMMDD.ERROR.log

    Remote Logging (TCP/UDP)

    If seaslog.appender is set to 2 (TCP) or 3 (UDP), logs are sent to remote_host:remote_port following the RFC5424 specification. The format is: <PRI>1 {timeStampWithRFC3339} {HostName} {loggerName}[{pid}]: {logInfo}

  5. Enable Performance Tracing

    master

    SeasLog can trace execution performance, recording wall time (wt), memory usage (mu), and call counts (ct) for functions and methods.

    Configuration

    • seaslog.trace_performance: (1=On, 0=Off) Enables tracing.
    • seaslog.trace_performance_sample_rate: Samples per thousand (Default: 10).
    • seaslog.trace_performance_min_wall_time: Minimum request execution time (ms) to trigger a trace (Default: 1000).
    • seaslog.trace_performance_min_function_wall_time: Minimum method execution time (ms) to include in trace (Default: 10).

    Example Trace Output

    2019-01-30 11:46:53 | INFO | 91390 | 5c518ea46e010 | 1548848813.299 | {"main()":{"wt":8848,"mu":20712},"1":[{"cm":"Class0::Method0","ct":2,"wt":2007,"mu":192}, ... ]}

    In the JSON payload:

    • cm: function_name (ClassName::MethodName)
    • wt: wall_time (ms)
    • mu: memory_usage (bytes)
    • ct: call_times
    2019-01-30 11:46:53 | INFO | 91390 | 5c518ea46e010 | 1548848813.299 | {"main()":{"wt":8848,"mu":20712},"1":[{"cm":"Class0::Method0","ct":2,"wt":2007,"mu":192},{"cm":"Class1::Method1","ct":1,"wt":1002,"mu":192},{"cm":"Class2::Method2","ct":1,"wt":1001,"mu":192},{"cm":"Class3::Method3","ct":1,"wt":1000,"mu":192},{"cm":"Class4::Method4","ct":1,"wt":1000,"mu":192}],"2":[{"cm":"Class5::Method5","ct":1,"wt":1000,"mu":192}],"3":[{"cm":"Class5::Recursion","ct":1,"wt":1000,"mu":3248}],"4":[{"cm":"Class5::Recursion","ct":1,"wt":1000,"mu":2952}],"5":[{"cm":"Class5::Recursion","ct":1,"wt":1000,"mu":2566}]}
  6. Customize log templates with preset variables

    master

    You can define a custom log format using seaslog.default_template. The template uses specific placeholders (prefixed with %) that are replaced at runtime.

    Default Template: %T | %L | %P | %Q | %t | %M (Format: {dateTime} | {level} | {pid} | {uniqid} | {timeStamp} | {logInfo})

    Available Variables

    TokenDescription
    %LLog Level
    %MLog Message
    %TDateTime (affected by seaslog.default_datetime_format)
    %tTimestamp (milliseconds)
    %QRequestId (unique ID for the request)
    %HHostName
    %PProcessId
    %DDomain:Port
    %RRequest URI
    %mRequest Method
    %IClient IP (Priority: HTTP_X_REAL_IP > HTTP_X_FORWARDED_FOR > REMOTE_ADDR)
    %FFileName:LineNo
    %UCurrent Memory Usage (bytes)
    %uPeak Memory Usage (bytes)
    %CClass::Action (Class::Method or function name)
    %BBasePath

    Note: If you haven't called SeasLog::setRequestId($string), %Q uses an internally generated unique ID.

    seaslog.default_template = "[%T]:%L %P %Q %t %M"
  7. Understand Log File Naming and Distribution

    master

    Log files are stored at: basePath / logger / {fileName}.log. The {fileName} defaults to the current date in YYYYMMDD format.

    The file structure depends on the seaslog.disting_type configuration:

    • seaslog.disting_type = 0 (Default): All logs are combined into one file per day: basePath / logger / 20140218.log.
    • seaslog.disting_type = 1: Logs are split by level: basePath / logger / 20140218.INFO.log, basePath / logger / 20140218.ERROR.log, etc.
  8. Configure SeasLog to output logs via TCP or UDP

    master

    To send logs remotely using the RFC5424 specification, set seaslog.appender to 2 (TCP) or 3 (UDP). When using these modes, you must specify the seaslog.remote_host and seaslog.remote_port.

    ;日志存储介质 1File 2TCP 3UDP (默认为1)
    seaslog.appender = 2
    
    ;接收ip 默认127.0.0.1 (当使用TCP或UDP时必填)
    seaslog.remote_host = "192.168.0.2"
    
    ;接收端口 默认514 (当使用TCP或UDP时必填)
    seaslog.remote_port = 514
  9. Configure Rsyslog to collect SeasLog files via imfile

    master

    If SeasLog is configured to write to files, use the Rsyslog imfile module to monitor the directory. Ensure the File path matches the seaslog.default_basepath and seaslog.default_logger configuration.

    #载入 imfile 模块
    module(load="imfile" PollingInterval="10")
    
    #使用 imfile 模块监听 `/var/log/www/default/` 文件夹下 .log 文件
    input(type="imfile"
        File="/var/log/www/default/*.log"
        Tag="tag1"
        Severity="error"
        Facility="local7")
  10. Configure Health Alerts (Email Warnings)

    master

    SeasLog can monitor logs and send email alerts when certain thresholds are met. This is configured in seaslog.ini and executed via a cron job.

    Configuration Steps

    1. Define SMTP Settings: Configure the [warning] section with your SMTP host, port, user, and password.
    2. Define Monitoring Rules: Create rules in the [analyz] section. Each rule (e.g., test1) requires:
      • module: The module to monitor.
      • level: The log level to watch (e.g., SEASLOG_ERROR).
      • bar: The threshold (number of occurrences) that triggers the alert.
      • mail_to: The recipient email(s).
    3. Setup Cron Job: Run the SeasLogAnalyzer.php script via crontab to perform the check.

    Example seaslog.ini snippet

    [warning]
    email[smtp_host] = smtp.163.com
    email[smtp_user] = seaslogdemo@163.com
    email[smtp_pwd] = seaslog#demo
    email[mail_to] = gaochitao@weiboyi.com
    
    [analyz]
    ; If 'test' module has > 3 ERROR logs, email neeke@php.net
    test1[module] = test
    test1[level] = SEASLOG_ERROR
    test1[bar] = 3
    test1[mail_to] = neeke@php.net

    Crontab Command

    # Run every day at 3:00 AM
    0 3 * * * /path/to/php /path/to/SeasLog/Analyzer/SeasLogAnalyzer.php
  11. Install SeasLog via Compilation, PECL, or Windows DLL

    master

    You can install SeasLog using one of the following three methods depending on your environment:

    1. Compile from Source

    Use phpize to prepare the extension, configure with your PHP path, and install.

    2. PECL Install

    Use the standard PECL command.

    3. Windows Environment

    Download the corresponding .dll file from the official PECL/SeasLog Windows page.

    ### Compile from Source
    $ /path/to/phpize
    $ ./configure --with-php-config=/path/to/php-config
    $ make && make install
    
    ### PECL Install
    $ pecl install seaslog
    
    ### Windows
    Download DLL from: http://pecl.php.net/package/SeasLog/1.8.4/windows