Kernel module log redirection method, electronic device, storage medium and product

By setting the log file path interface and the ring buffer mechanism in the kernel module, the log output path is dynamically managed, which solves the problem of low troubleshooting efficiency caused by mixed logging in the kernel module, and achieves efficient and reliable log management and system performance improvement.

CN121412073BActive Publication Date: 2026-02-24JINAN INSPUR DATA TECH CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202511974686.9
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2025-12-25
Publication Date
2026-02-24
Estimated Expiration
2045-12-25

AI Technical Summary

Technical Problem

In the server field, as the number of customized modules increases, the mixed recording of kernel module logs leads to low efficiency in troubleshooting and makes it difficult to achieve module-level log isolation management. Existing log redirection solutions suffer from problems such as system crashes, low efficiency, high resource consumption, and log format incompatibility.

Method used

By setting the log file path interface in the kernel module, the system can dynamically determine whether the log content contains a valid file path, thereby achieving intelligent management of the log output path. Log redirection is enabled only when needed and automatically released. A ring buffer mechanism and batch I/O optimization technology are adopted to ensure log format compatibility and efficient utilization of system resources.

Benefits of technology

It achieves isolated, highly reliable, and high-performance management of kernel module logs, improving troubleshooting efficiency, reducing system resource consumption, and ensuring consistent log format and system stability.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121412073B_ABST
    Figure CN121412073B_ABST
Patent Text Reader

Abstract

The application discloses a kernel module log redirection method, an electronic device, a storage medium and a product, relates to the technical field of computers, and enables the log to be flexibly switched between different output targets by realizing dynamic identification and on-demand redirection of a log path in a kernel state, thereby avoiding the problem of tight coupling between log output and system logs in a traditional scheme. After the log content carries effective path information, the log content can autonomously determine a storage position, realizes log isolation between modules, and prevents different subsystem logs from interfering with each other. After the redirection is completed, the default output is automatically restored, the complexity of manual configuration and file operation is reduced, and the automation level of log processing is improved. Therefore, the independence, high reliability and efficient management of log output are realized, and the risk of system crash and performance loss is significantly reduced.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of computer technology, and in particular to a kernel module log redirection method, electronic device, storage medium, and product. Background Technology

[0002] In the server field, to meet customized business needs, it is often necessary to deeply develop and maintain Linux kernel modules. These customized modules are usually dynamically loaded into the operating system as kernel objects (KOs). The logs generated during the operation of kernel modules are the core basis for problem localization and performance analysis. However, under the default mechanism, all module logs are mixed and recorded in the system log. When the number of customized modules being maintained increases, log coupling leads to low efficiency in troubleshooting, especially when the log level is debug. It is necessary to filter the target module logs from massive system logs, and it is difficult to achieve module-level log isolation management. Summary of the Invention

[0003] This application provides a kernel module log redirection method, electronic device, storage medium, and product to at least solve problems such as log coupling, system crashes, and low efficiency in related technologies, and to achieve isolated, highly reliable, and high-performance management of kernel module logs.

[0004] This application provides a kernel module log redirection method, the method comprising:

[0005] In response to the generation of logs, determine whether to write a valid file path in the log content for each log entry based on its log type;

[0006] When the kernel module receives the target log, it parses the log content of the target log and determines whether there is a valid file path in the log content;

[0007] If a valid file path exists in the log content of the target log, then the target log path is configured through the log file path interface according to the valid file path, log redirection is enabled, the target log is recorded to the target log file pointed to by the target log path, and log redirection is disabled by setting the log file path interface to empty.

[0008] If a valid file path does not exist in the log content of the target log, the log file path interface will not enable log redirection and the target log will be recorded in the system log.

[0009] This application also provides an electronic device, comprising: a memory for storing a computer program; and a processor for implementing the steps of any of the above-described kernel module log redirection methods when executing the computer program.

[0010] In response to the generation of logs, determine whether to write a valid file path in the log content for each log entry based on its log type;

[0011] When the kernel module receives the target log, it parses the log content of the target log and determines whether there is a valid file path in the log content;

[0012] If a valid file path exists in the log content of the target log, then the target log path is configured through the log file path interface according to the valid file path, log redirection is enabled, the target log is recorded to the target log file pointed to by the target log path, and log redirection is disabled by setting the log file path interface to empty.

[0013] If a valid file path does not exist in the log content of the target log, the log file path interface will not enable log redirection and the target log will be recorded in the system log.

[0014] This application also provides a computer-readable storage medium storing a computer program, wherein the computer program, when executed by a processor, implements the steps of any of the above-described kernel module log redirection methods:

[0015] In response to the generation of logs, determine whether to write a valid file path in the log content for each log entry based on its log type;

[0016] When the kernel module receives the target log, it parses the log content of the target log and determines whether there is a valid file path in the log content;

[0017] If a valid file path exists in the log content of the target log, then the target log path is configured through the log file path interface according to the valid file path, log redirection is enabled, the target log is recorded to the target log file pointed to by the target log path, and log redirection is disabled by setting the log file path interface to empty.

[0018] If a valid file path does not exist in the log content of the target log, the log file path interface will not enable log redirection and the target log will be recorded in the system log.

[0019] This application also provides a computer program product, including a computer program that, when executed by a processor, implements the steps of any of the above-described kernel module log redirection methods:

[0020] In response to the generation of logs, determine whether to write a valid file path in the log content for each log entry based on its log type;

[0021] When the kernel module receives the target log, it parses the log content of the target log and determines whether there is a valid file path in the log content;

[0022] If a valid file path exists in the log content of the target log, then the target log path is configured through the log file path interface according to the valid file path, log redirection is enabled, the target log is recorded to the target log file pointed to by the target log path, and log redirection is disabled by setting the log file path interface to empty.

[0023] If a valid file path does not exist in the log content of the target log, the log file path interface will not enable log redirection and the target log will be recorded in the system log.

[0024] This application achieves intelligent management of log output paths by setting a log file path interface in the kernel module and dynamically determining whether the log content contains a valid file path throughout the entire process of log generation, parsing, and writing. When a valid file path is detected in the log content, the system automatically configures the target log path in the log file path interface and enables log redirection, so that the log is recorded to the specified target log file. When no valid file path is found in the log content, the log is recorded to the system log by default. This process automatically disables redirection after the log is written, restoring the default output state. This application realizes dynamic configurability and automatic switching of log output paths, avoiding the log coupling problem caused by the strong binding between log recording paths and system logs in traditional kernel modules. At the same time, since log redirection is only enabled when needed and automatically released after recording is completed, system resource consumption and file handle conflicts are reduced, significantly improving the reliability of log management. In addition, by directly completing log path parsing and redirection control within the kernel module, frequent user-mode intervention or complex configuration operations are avoided, thereby improving log processing efficiency and overall system performance. Therefore, this method achieves isolated, highly reliable, and high-performance management of kernel module logs. Attached Figure Description

[0025] To more clearly illustrate the technical solutions in the embodiments of the present invention, the accompanying drawings used in the description of the embodiments will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0026] Figure 1 This is a diagram illustrating the application environment of a kernel module log redirection method in one embodiment of this application.

[0027] Figure 2 This is a flowchart illustrating a kernel module log redirection method in one embodiment of this application;

[0028] Figure 3 This is a logic diagram of a single log file path interface control in one embodiment of this application;

[0029] Figure 4 This is an architecture diagram of producer-consumer secure write in one embodiment of this application;

[0030] Figure 5 This is a logic diagram of a buffer for reading log data from the circular buffer and writing log content to the target log file or the system log in one embodiment of this application;

[0031] Figure 6 This is a logical diagram showing the buffer's capacity to hold log entries in one embodiment of this application;

[0032] Figure 7 This is a logical diagram of a buffer that cannot hold log entries in one embodiment of this application;

[0033] Figure 8 This is a flowchart of timestamp generation in one embodiment of this application;

[0034] Figure 9 This is a logic diagram of a resource unified management mechanism based on a global context in one embodiment of this application;

[0035] Figure 10 This is a structural block diagram of a kernel module log redirection device in one embodiment of this application;

[0036] Figure 11 This is an internal structural diagram of a computer device in one embodiment of this application. Detailed Implementation

[0037] To make the objectives, technical solutions, and advantages of this application clearer, the following detailed description is provided in conjunction with the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the scope of this application.

[0038] It should be noted that, in the description of this application, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. The terms "first," "second," etc., in this application are used to distinguish similar objects and are not used to describe a specific order or sequence.

[0039] To enable those skilled in the art to better understand the present application, the present application will be further described in detail below with reference to the accompanying drawings and specific embodiments.

[0040] The relevant technology is a simple log redirection solution: by adding a log file path configuration interface to the module, logs are written directly to a specified file. However, this solution has significant drawbacks: First, it carries the risk of interrupting the context; log write operations (such as file I / O) may be executed in an interrupted context, triggering the BUG_ON assertion in the check_irqs_on() function and causing a system crash. Second, it is inefficient, as each log entry is written to a separate file, and frequent system calls consume a large amount of CPU resources. Third, it is complex to control, requiring the maintenance of both the "path configuration" and "redirection switch" interfaces, increasing the cost of use. Fourth, it suffers from log format incompatibility; redirected logs lack the timestamp information of the system log standard, making it difficult to link and analyze with other logs. Fifth, it suffers from poor data consistency, and log truncation and corruption are prone to occur in multi-producer scenarios.

[0041] The kernel module log redirection method provided in this application can be applied to, for example... Figure 1In the application environment shown, this solution addresses the problems of log coupling, system crashes, and low efficiency in existing solutions through five core technologies: single interface control, secure context writing, efficient data buffering, batch IO optimization, and format compatibility. It achieves isolated, highly reliable, and high-performance management of kernel module logs. Specifically, the interface layer provides a single configuration entry point, adaptively switching the log output target based on the existence of configuration values. When the configuration is valid, targeted storage is enabled; when the configuration is empty, the default output is restored. The core layer employs a circular buffer mechanism as a data transfer carrier, leveraging its native thread-safe characteristics to achieve lock-free data transfer and supporting asynchronous operations for producer-side writing and consumer-side reading. The producer automatically appends standardized timestamps when generating logs to ensure format compatibility with system logs. After formatting, the data is pushed to the circular buffer, making the operation lightweight to adapt to various execution contexts. The consumer runs in a secure execution context, sensing changes in buffered data through a blocking wait mechanism. It employs a batch accumulation strategy, performing a one-time persistence operation when the data volume reaches a preset threshold or meets trigger conditions, reducing the frequency of interaction with the storage medium. The resource management layer centrally maintains the state of all components through a global context structure. During initialization, it prepares resources such as buffers and synchronization mechanisms. During exit, it ensures the complete persistence of remaining data and releases resources. sysfs is a virtual file system that provides a way to access kernel data structures, allowing user-space programs to view and control system devices and resources.

[0042] like Figure 2 As shown, an embodiment of this application provides a kernel module log redirection method, which includes the following steps:

[0043] Step S1: In response to the generation of logs, determine whether to write a valid file path in the log content for each log based on its log type;

[0044] Step S2: In response to the kernel module receiving the target log, parse the log content of the target log and determine whether there is a valid file path in the log content;

[0045] Step S3: In response to the existence of a valid file path in the log content of the target log, configure the target log path in the log file path interface according to the valid file path, enable log redirection, record the target log to the target log file pointed to by the target log path, and disable log redirection by setting the log file path interface to empty.

[0046] In step S4, if there is no valid file path in the log content of the target log, the log file path interface will not enable log redirection and the target log will be recorded in the system log.

[0047] This invention achieves intelligent management of log output paths by setting a log file path interface in the kernel module and dynamically determining whether the log content contains a valid file path throughout the entire process of log generation, parsing, and writing. When a valid file path is detected in the log content, the system automatically configures the target log path in the log file path interface and enables log redirection, so that the log is recorded to the specified target log file. When no valid file path is found in the log content, the log is recorded to the system log by default. This process automatically disables redirection after the log is written, restoring the default output state. This application realizes dynamic configurability and automatic switching of log output paths, avoiding the log coupling problem caused by the strong binding between log recording paths and system logs in traditional kernel modules. At the same time, since log redirection is only enabled when needed and automatically released after recording is completed, system resource consumption and file handle conflicts are reduced, significantly improving the reliability of log management. In addition, by directly completing log path parsing and redirection control within the kernel module, frequent user-space intervention or complex configuration operations are avoided, thereby improving log processing efficiency and overall system performance. Therefore, this method achieves isolated, highly reliable, and high-performance management of kernel module logs.

[0048] This application exposes only a single log file path (log_path) system file interface (implemented based on sysfs), and adaptively controls the redirection state through the "existence" of the path: when log_path is an empty string, log redirection is automatically turned off and the log is output to the system log; when a valid file path is written to log_path, path verification and file opening operations are automatically performed, and redirection is enabled after success; if the path is invalid (such as insufficient permissions or the path does not exist), the original log output method is maintained and an error is returned.

[0049] like Figure 3 As shown, the single log file path interface control logic includes a three-tier architecture: "interface layer - verification layer - execution layer".

[0050] (1) Interface layer: Only one read and write attribute, / sys / fs / log_path, is provided, which supports cat to read the current path and echo to write to the new path;

[0051] (2) Verification layer: After receiving the path, verify the path length (≤256 bytes) and file writability (attempt to open via filp_open);

[0052] (3) Execution layer: If the verification passes, update the path and file pointer in the log context and trigger redirection; if the verification fails, maintain the original state and output the error log through printk.

[0053] Specifically, by default, `log_path` is empty, indicating that log redirection is not enabled, and logging will continue to use the old logic and be recorded in the system log. When `log_path` is not empty, configuring a target log path through the `log_path` interface enables log redirection, and logs will be recorded in the target log path. If a valid target log path is already configured in `log_path`, and then the `log_path` interface is set to empty, log redirection is disabled, and logging will continue to use the old logic and be recorded in the system log. If a valid target log path is already configured in `log_path`, and a new target log path is configured through the `log_path` interface, the execution layer will first close the old target log file, update relevant resources, and then redirect the logs to the new target log path.

[0054] In this embodiment, in response to the existence of a valid file path in the log content of the target log, the target log path is configured in the log file path interface according to the valid file path, and log redirection is enabled, including:

[0055] After receiving a valid file path from the log file path interface, verify the length of the valid file path and the writability of the file pointed to by the valid file path;

[0056] If the length of the valid file path is acceptable and the file pointed to by the valid file path is writable, the verification is considered successful; otherwise, the verification is considered unsuccessful.

[0057] If the verification passes, the path and file pointer in the log context are updated, triggering redirection to begin;

[0058] In response to verification failure, the state of the path and file pointer in the log context remains unchanged, and an error log is output.

[0059] The path validity verification mechanism prevents logs from being redirected to invalid paths or read-only files, ensuring the accessibility and write safety of log files. This mechanism intercepts invalid paths at the kernel level in advance, avoiding file handle errors or kernel write failures due to incorrect paths, thereby improving system fault tolerance and the robustness of log operations. Simultaneously, error log prompts help developers quickly locate the source of problems, improving system maintenance efficiency and reliability.

[0060] In this embodiment, when log redirection is enabled, the following is also included:

[0061] Check if the log file path interface has been configured with an old target log path;

[0062] If the log file path interface has an old target log path configured, configure the new target log path through the log file path interface, close the old target log file pointed to by the old target log path, update the relevant resources, and redirect the logs to the new target log file pointed to by the new target log path.

[0063] If the log file path interface does not have an old target log path configured, the target log path is configured according to the valid file path through the log file path interface, and the logs are redirected to the target log file pointed to by the target log path.

[0064] By introducing an orderly management mechanism for path switching, resource consistency and data security are ensured during log file replacement. Closing the old file and releasing its handle prevents resource consumption and data conflicts, and avoids file handle leakage and log overwriting. Smooth switching between old and new paths ensures stable system operation under high load or frequent path change scenarios, achieving highly reliable and resource-safe log redirection management.

[0065] In this embodiment, the method further includes:

[0066] The generated logs are formatted and timestamps are added to form log data.

[0067] Write log data to a circular buffer;

[0068] When recording the target log to the target log file or system log pointed to by the target log path, the interrupt is enabled based on the kernel work queue control of the log content writing process, and log data is read from the ring buffer and the log content is written to the buffer of the target log file or system log.

[0069] By decoupling log generation and writing, the real-time performance of log processing and system efficiency are significantly improved. The addition of formatting and timestamps ensures that log records have a uniform format and accurate time signature, facilitating problem tracing and analysis. A circular buffer enables cached management of logs, preventing disk I / O blocking caused by high-frequency writes. Combined with the asynchronous scheduling mechanism of the kernel work queue, CPU load is effectively balanced, improving the throughput performance and overall stability of the logging system.

[0070] like Figure 4 As shown, a circular buffer can connect the producer (log generator) and the consumer (log writer), thus achieving data caching. This application adopts a "producer-consumer" model to separate log generation and writing.

[0071] (1) Producer (log generation end): The log formatting and timestamp addition are completed in the redirection function printk_redirect, and the complete log data is written to the circular buffer (kfifo). The operation is lightweight and has no risk of sleep, and it is compatible with all kernel contexts.

[0072] (2) Consumer (log writer): Implemented based on kernel workqueue, running in process context (interrupt enabled), reads data from the circular buffer and performs file writing.

[0073] Persisting logs involves executing kernel_write, which writes data from memory to disk, thus writing the log content to the target log file.

[0074] In this embodiment, enabling interrupts for the process writing kernel work queue control log content includes:

[0075] When the remaining space in the buffer is less than the first threshold, blocking and waiting are implemented through a waiting queue (wait_queue);

[0076] When there is no data in the buffer, the process that controls the writing of log content enters a sleep state. When a new log is generated, the process that controls the writing of log content is awakened.

[0077] Specifically, by employing a wait queue and sleep mechanism, the log writing process can be automatically scheduled based on the buffer status, reducing unnecessary CPU polling and resource contention. The system maintains high efficiency during both log bursts and idle periods, without degrading system performance due to excessive kernel resource consumption. This mechanism implements adaptive flow control for log writing, ensuring both log data integrity and system operational balance.

[0078] This application implements consumer blocking and waiting through a wait queue. When the buffer is empty, the consumer goes to sleep; the producer wakes up the consumer after writing data, avoiding busy waiting that consumes CPU. By decoupling "high-risk file I / O" from "high-concurrency log generation" through a work queue, it ensures that all I / O operations are executed in a safe process context, completely avoiding the risk of crashes caused by interrupts being disabled.

[0079] like Figure 5 As shown, in this embodiment, the buffer for reading log data from the circular buffer and writing the log content to the target log file or system log includes:

[0080] Get the number of memory pages in bytes used to store the log content in the buffer of the target log file or system log, and set the number of bytes in the circular buffer to be equal to the number of memory pages.

[0081] When writing log entries from the circular buffer to the buffer, read a single log entry from the circular buffer, obtain the number of bytes in a single log entry, obtain the remaining space in the buffer, and compare the number of bytes in the log entry with the remaining space.

[0082] When the remaining space is greater than or equal to the number of entries in bytes, it is determined that the buffer can hold a single log entry, the single log entry is written to the buffer and the current position of the single log entry is updated;

[0083] If the remaining space is less than the number of bytes for an entry, and it is determined that the buffer cannot hold a single log entry, the buffer is refreshed, the remaining space in the buffer is retrieved again, and the number of bytes for an entry is compared with the remaining space.

[0084] Specifically, by precisely controlling the buffer size and space utilization, memory fragmentation is reduced and data write continuity is ensured. Dynamically comparing log entries with remaining space avoids overflow risks, making the log writing process more stable and efficient. This solution optimizes kernel memory allocation and caching strategies, improving system performance and security in high-frequency log writing scenarios.

[0085] This application designs a batch write buffer that matches the memory page size (default 4096 bytes) and optimizes I / O operations through an "accumulation-flush" strategy. A built-in `write_buf` buffer (4096 bytes) is incorporated into the log context, consistent with the Linux memory page size, reducing I / O overhead caused by page splits. After reading log entries from kfifo, the consumer checks the number of bytes in the entry against the remaining space in the buffer: if there is enough space, the entry is copied to the buffer and `write_pos` (current position) is updated; otherwise, the buffer is flushed before writing.

[0086] like Figure 5 As shown, in this embodiment, the buffer for reading log data from the circular buffer and writing the log content to the target log file or system log further includes:

[0087] When the remaining space is greater than or equal to the number of bytes in the circular buffer, read multiple log data entries equal to the number of bytes in the circular buffer and write these multiple log data entries into the buffer in batches.

[0088] After writing multiple log data entries to the buffer in batches, the buffer is flushed to determine if there is any remaining log data.

[0089] If there is remaining log data in the circular buffer, continue reading multiple log data entries from the circular buffer; otherwise, terminate the process after flushing the buffer.

[0090] The batch write mechanism reduces disk I / O operations and interrupts, improving write efficiency and system throughput. By combining batch processing with cache flushing, log data writing becomes smoother and more consistent, reducing write latency. This design is suitable for complex kernel scenarios with high-frequency log output, significantly improving overall system performance and stability.

[0091] By merging multiple small log data into a single 4096-byte batch write, the number of system calls is reduced by more than 80%, significantly reducing CPU and IO overhead.

[0092] like Figure 5 As shown, in this embodiment, the buffer for reading log data from the circular buffer and writing the log content to the target log file or system log further includes:

[0093] When reading the first log entry from the circular buffer, determine whether the first log entry is an entry that was truncated when the previous memory page of the buffer was full;

[0094] If the first log entry is a truncated entry when the previous memory page of the buffer is full, then the first log entry will be written separately into the buffer to avoid log formatting errors.

[0095] The exception handling method in this application is as follows: unterminated log entries (such as entries truncated when the buffer is full) are handled separately to avoid log format corruption.

[0096] Specifically, by detecting and individually processing truncated log entries, log content corruption or loss caused by cross-page writes is prevented, ensuring the integrity and chronological order of log records. This mechanism ensures that log files maintain readability and consistency even under continuous large-scale data writes, improving the accuracy of subsequent analysis and debugging.

[0097] In this embodiment, obtaining the remaining space of the buffer includes:

[0098] Set the write pointer to indicate the end of the stored data in the buffer;

[0099] Get the position of the write pointer in the buffer. Before the write pointer is the stored data in the buffer, and after the write pointer is the remaining space in the buffer.

[0100] The write pointer mechanism enables real-time management of the buffer space state, precisely controlling the data write position and preventing out-of-bounds operations. Through dynamic pointer updates and space calculations, it improves buffer utilization and data storage security, making the log writing process more efficient and reliable.

[0101] like Figure 6As shown, when the buffer can hold the log entries in the circular buffer kfifo, the log entries are directly copied to the buffer and the write pointer write_pose is updated.

[0102] like Figure 7 As shown, when the buffer cannot hold the log entries in the circular buffer kfifo, the buffer is flushed first, then the log entries are copied to the buffer and the write pointer write_pos is updated.

[0103] In this embodiment, the method further includes:

[0104] The buffer is flushed when the memory page preceding it is full.

[0105] After writing multiple log data entries (number of bytes) to the circular buffer in batches, flush the buffer.

[0106] When the target log is recorded to the target log file pointed to by the target log path or after the system log is switched, the buffer is refreshed;

[0107] When a kernel module exits, the buffer is flushed.

[0108] Among these features, a multi-time refresh mechanism ensures that all log data is promptly written to disk or transmitted, preventing the loss of residual data in the cache. A multi-condition trigger design improves the data consistency and reliability of the logging system at different operational stages, guaranteeing log integrity and traceability during module operation and exit.

[0109] The refresh trigger conditions for this application are as follows: kernel_write will be triggered if any of the following conditions are met: ① The buffer is full (write pointer write_pos == 4096); ② Batch processing is completed (the circular buffer kfifo is empty); ③ Log file is switched (log_path is updated); ④ Kernel module exits.

[0110] like Figure 8 As shown, in this embodiment, the generated logs are formatted and timestamps are added to form log data, including:

[0111] Get the microsecond-level time of the generated logs, convert the microsecond-level time to the local millisecond-level time, convert the local millisecond-level time to structured time, and extract the month, date, hour, minute, and second information;

[0112] The extracted month, date, hour, minute, and second information are used to form a timestamp using a preset time format. When there is missing time information, a placeholder is used to replace it.

[0113] Combine timestamps with log content, perform format validation on the timestamps, and output the results.

[0114] This solution achieves high-precision time synchronization and unified time format output, enabling log records to contain accurate time-series information, facilitating rapid problem location and event reproduction. The standardized timestamp format improves the comparability and analysis efficiency of cross-module logs, thereby enhancing system monitoring and debugging capabilities.

[0115] Existing redirection schemes lack timestamps or have formats inconsistent with system logs, making it impossible to correlate and analyze module logs and system logs by time dimension. This application automatically adds timestamps compatible with Linux system logs during the log formatting stage, achieving "uniform format and time alignment".

[0116] (1) Timestamp format: Uses the format [MMM DD HH:MM:SS.sss] (e.g., [Jan 05 14:30:25.123]), which is completely consistent with the format of / var / log / messages;

[0117] (2) High-precision time acquisition: Microsecond-level time (struct timeval) is obtained through do_gettimeofday and converted to millisecond precision (tv_usec / 1000) to balance precision and performance;

[0118] (3) Time conversion: Convert the second-level time (tv_sec) to structured time (structtm) using time_to_tm, and extract the month, date, hour, minute and second information;

[0119] (4) Month abbreviation handling: A custom month_abbrev array (Jan to Dec) is used to replace the month_names variable that is not exported by the kernel to ensure compatibility;

[0120] (5) Fault tolerance mechanism: If time acquisition fails (e.g., do_gettimeofday returns an exception), [unknown time] is automatically used as a placeholder to avoid log generation failure.

[0121] In this embodiment, the method further includes:

[0122] When a kernel module is unloaded, all resources are traversed through the context pointer, and resources are released in the following order: stop the work queue service, release buffered data, close files, destroy the ring buffer, and release the context.

[0123] Among these measures, a rigorous resource reclamation process ensures that system resources are completely released when modules are unloaded, preventing memory leaks, handle remnants, and potential deadlocks. A step-by-step release mechanism guarantees controllability and security during the exit process, improving the long-term operational stability of the system and the reusability of modules, and ensuring the safe and reliable exit of the log system at the end of its lifecycle.

[0124] In this embodiment, the method further includes:

[0125] Before enabling log redirection, a mutex lock is requested when the log context enters the configuration phase. The mutex lock protects the update operations of the log context's path pointer and file handle.

[0126] After completing the writing of the target log file and disabling log redirection, the mutex lock is released after the log path interface is set to null.

[0127] When other threads attempt to modify the log path interface, if the mutex is held, they enter a waiting state until it is unlocked.

[0128] The release of the mutex lock ensures thread safety during the log path configuration and redirection state switching process.

[0129] In this embodiment, the method further includes:

[0130] During log redirection, the number of writes and the number of bytes written to the target log file are counted.

[0131] When the number of writes exceeds a preset threshold, a log rotation file is generated, the current file is closed, and a new target log file is started for writing, in order to prevent performance degradation or file corruption caused by a single log file becoming too large.

[0132] like Figure 9 As shown, this application designs a global context structure as a resource container based on a unified resource management mechanism using a global context. This structure centrally manages all components and states required by the log-directed system, achieving unified lifecycle control of resources. This mechanism ensures resource consistency through a three-stage management process: initialization, runtime, and exit.

[0133] (1) Initialization phase: When the module is loaded, all resources are created and associated through a single entry function, including circular buffer (kfifo), work queue, wait queue, batch write buffer, file pointer, etc., to avoid resource misconfiguration caused by scattered initialization;

[0134] (2) Runtime phase: All functional modules (producer, consumer, interface layer) obtain resources by accessing the global context to ensure the uniqueness of resource references; state changes (such as file path updates and buffer position adjustments) are completed within the context, and concurrency safety is ensured through atomic variables or boundary checks;

[0135] (3) Exit phase: When the module is unloaded, all resources are traversed through the context pointer and resources are released in the order of "stop service first → release data then → destroy component last" to avoid dangling references or data loss.

[0136] This approach abstracts dispersed system resources into a unified context, and solves the maintenance complexity caused by resource fragmentation through closed-loop management of "creation-use-destruction". At the same time, it provides standardized interfaces for function expansion. For example, adding a log encryption function only requires adding an encryption status field to the context.

[0137] Initialization: The module_init function calls kzalloc to create a struct log_ctx instance, and initializes each resource field in sequence (such as kfifo_alloc initializing the buffer and INIT_WORK initializing the work queue).

[0138] At runtime: The producer accesses the FIFO to write data through the log_ctx pointer, the consumer reads data and updates write_pos through the same pointer, and the interface layer updates file_path and fp through pointers;

[0139] Exit: The module_exit function executes the following steps sequentially via the log_ctx pointer: flush_work (stop the work queue) → flush_write_buffer (release buffered data) → filp_close (close the file) → kfifo_free (destroy the buffer) → kfree (release the context).

[0140] This application is implemented as a Linux kernel module, supporting kernel versions 3.10 and above. The core code structure includes four main modules: "log context management, sysfs interface implementation, producer-consumer logic, and batch write optimization". The specific implementation steps are as follows:

[0141] 1) Data structure definition

[0142] Define a global context structure called struct log_ctx to encapsulate all log-related resources, ensuring centralized management and fast access to resources.

[0143] struct log_ctx{

[0144] struct file*fp; / / Pointer to the log file

[0145] char* file_path; / / Current log path

[0146] struct kobject*kobj; / / sysfs object

[0147] struct work_struct write_work; / / Consumer work queue

[0148] struct kfifo fifo; / / Circular buffer

[0149] char write_buf[WRITE_BUF_SIZE]; / / Batch write buffer (4096 bytes)

[0150] unsigned int write_pos; / / Current position of the buffer

[0151] wait_queue_head_t wait_queue; / / wait queue

[0152] atomic_t shutdown; / / Module exit flag (atomic variable)

[0153] };

[0154] static struct log_ctx*log_ctx= NULL; / / Global context instance.

[0155] 2) Module initialization process

[0156] Resource initialization is completed during module loading (module_init). The specific steps are as follows:

[0157] Context allocation: Allocate a struct log_ctx instance via kzalloc, and initialize all fields to 0;

[0158] kfifo initialization: Call kfifo_alloc(&log_ctx->fifo, FIFO_SIZE, GFP_KERNEL) to create a 16384-byte circular buffer;

[0159] Synchronization mechanism initialization: The wait queue is initialized via init_waitqueue_head, and the exit flag is set via atomic_set(&log_ctx->shutdown, 0);

[0160] Work queue initialization: The consumer function is bound via INIT_WORK(&log_ctx->write_work, log_write_worker), and the work queue is started via schedule_work;

[0161] sysfs interface creation: The kobject_create_and_add call creates the / sys / fs / o2cb directory, and the sysfs_create_group registers the log_path attribute;

[0162] State initialization: Set log_ctx->file_path = NULL and log_ctx->fp = NULL, which disables redirection by default.

[0163] 3) Log generation and writing process

[0164] Producer logic (printk_recirect):

[0165] Call format_timestamp to generate a timestamp and append it to the header of the log buffer;

[0166] Use vsnprintf to format the log content, ensuring the total length does not exceed LOG_ITEM_MAX_LEN (512 bytes).

[0167] Check if log_path is valid: if valid and kfifo has enough space, write to the buffer via kfifo_in and call wake_up_interruptible to wake up the consumer; if invalid, call the standard vprintk to output to the system log.

[0168] Consumer logic (log_write_worker):

[0169] Enter a loop to wait: Block using wait_event_interruptible until kfifo has data or receives an exit signal;

[0170] Data reading: Call kfifo_out to read log entries from the buffer, up to a maximum of LOG_ITEM_MAX_LEN bytes;

[0171] Batch accumulation: Determine if an entry can be placed into write_buf. If it can, copy and update write_pos; otherwise, flush the buffer first.

[0172] Buffer flush: When the flush condition is met, flush_write_buffer is called to execute kernel_write and reset write_pos;

[0173] Exit procedure: Upon receiving a shutdown signal, refresh the remaining data and exit the loop.

[0174] 4) sysfs interface implementation

[0175] log_path_show (read interface): Returns the current log_ctx->file_path, or an empty string if it is empty;

[0176] log_path_store (write interface):

[0177] The path input by the user is received, and flush_write_buffer is called first to flush the buffer;

[0178] Close the old log file (filp_close) and release the memory in the old path;

[0179] If the input is empty, set log_ctx->file_path = NULL and log_ctx->fp = NULL to disable redirection;

[0180] If the input is a valid path, call filp_open to open the file in O_WRONLY|O_CREAT|O_APPEND mode, update file_path and fp, and wake up the consumer.

[0181] 5) Module Exit Process

[0182] Ensure resources are safely released during module unloading (module_exit):

[0183] Send an exit signal: atomic_set(&log_ctx->shutdown, 1), and call wake_up_interruptible to wake up the consumer;

[0184] Waiting for the consumer to finish: flush_work(&log_ctx->write_work) ensures that the work queue has processed all data;

[0185] Refresh remaining data: Call flush_write_buffer to write the logs that have not been flushed in write_buf;

[0186] Resource release: Close the log file, release the file_path memory, destroy kfifo, and release the LogContext instance.

[0187] The advantages of this application compared to existing solutions are specifically reflected in the following aspects:

[0188] (1) Log isolation management: The module logs are output in a targeted manner through a single path interface, which solves the problem of multi-module log coupling and improves the efficiency of fault diagnosis by more than 80%.

[0189] (2) Improved system stability: Process context writing based on work queues completely avoids system crashes caused by interrupt disabling, and the module's operational stability reaches 99.99%;

[0190] (3) Significant performance optimization: The batch write mechanism reduces the number of system calls by 80% and CPU utilization by 50%-70%;

[0191] (4) High ease of use: Redirection can be automatically enabled / disable simply by configuring the log path, without the need for additional operation switches, thus reducing the cost of use;

[0192] (5) Good format compatibility: The timestamp is completely consistent with the system log, supports cross-log linkage analysis, and is compatible with existing log analysis tools.

[0193] The aforementioned kernel module log redirection method achieves intelligent management of log output paths by setting a log file path interface in the kernel module and dynamically determining whether the log content contains a valid file path throughout the entire process of log generation, parsing, and writing. When a valid file path is detected in the log content, the system automatically configures the target log path in the log file path interface and enables log redirection, allowing the log to be recorded in the specified target log file. When no valid file path is found in the log content, the log is recorded in the system log by default. This process automatically disables redirection after the log is written, restoring the default output state. This application implements dynamic configurability and automatic switching of the log output path, avoiding the log coupling problem caused by the strong binding between the log recording path and the system log in traditional kernel modules. Furthermore, since log redirection is only enabled when needed and automatically released after recording, it reduces system resource consumption and file handle conflicts, significantly improving the reliability of log management. In addition, by directly completing log path parsing and redirection control within the kernel module, frequent user-mode intervention or complex configuration operations are avoided, thereby improving log processing efficiency and overall system performance. Therefore, this method achieves isolated, highly reliable, and high-performance management of kernel module logs.

[0194] Through the above description of the embodiments, those skilled in the art can clearly understand that the methods according to the above embodiments can be implemented by means of software plus necessary general-purpose hardware platforms. Of course, they can also be implemented by hardware, but in many cases the former is a better implementation method.

[0195] In one embodiment, such as Figure 10 As shown, a kernel module log redirection device 10 is provided, including: a log path identification module 1, a log path parsing module 2, a log redirection control module 3, a system log writing module 4, a log buffering and writing module 5, and a resource release management module 6.

[0196] The log path identification module 1 is used to determine whether to write a valid file path in the log content for each log entry based on its log type when a log is generated.

[0197] Log path parsing module 2 is used to parse the log content of the target log and determine whether there is a valid file path in the log content when the kernel module receives the target log.

[0198] Log redirection control module 3 is used to respond to the existence of a valid file path in the log content of the target log. If the valid file path exists, it configures the target log path in the log file path interface, enables log redirection, records the target log to the target log file pointed to by the target log path, and disables log redirection by setting the log file path interface to empty.

[0199] The system log writing module 4 is used to respond to the fact that there is no valid file path in the log content of the target log. In this case, the log file path interface does not enable log redirection and the target log is recorded to the system log.

[0200] In this embodiment, in response to the existence of a valid file path in the log content of the target log, the target log path is configured in the log file path interface according to the valid file path, and log redirection is enabled, including:

[0201] After receiving a valid file path from the log file path interface, verify the length of the valid file path and the writability of the file pointed to by the valid file path;

[0202] If the length of the valid file path is acceptable and the file pointed to by the valid file path is writable, the verification is considered successful; otherwise, the verification is considered unsuccessful.

[0203] If the verification passes, the path and file pointer in the log context are updated, triggering redirection to begin;

[0204] In response to verification failure, the state of the path and file pointer in the log context remains unchanged, and an error log is output.

[0205] In this embodiment, when log redirection is enabled, the following is also included:

[0206] Check if the log file path interface has been configured with an old target log path;

[0207] If the log file path interface has an old target log path configured, configure the new target log path through the log file path interface, close the old target log file pointed to by the old target log path, update the relevant resources, and redirect the logs to the new target log file pointed to by the new target log path.

[0208] If the log file path interface does not have an old target log path configured, the target log path is configured according to the valid file path through the log file path interface, and the logs are redirected to the target log file pointed to by the target log path.

[0209] In this embodiment, the log buffering and writing module 5 is used for:

[0210] The generated logs are formatted and timestamps are added to form log data.

[0211] Write log data to a circular buffer;

[0212] When recording the target log to the target log file or system log pointed to by the target log path, the interrupt is enabled based on the kernel work queue control of the log content writing process, and log data is read from the ring buffer and the log content is written to the buffer of the target log file or system log.

[0213] In this embodiment, enabling interrupts for the process writing kernel work queue control log content includes:

[0214] When the remaining space in the buffer is less than the first threshold, blocking and waiting are implemented through a waiting queue (wait_queue);

[0215] When there is no data in the buffer, the process that controls the writing of log content enters a sleep state. When a new log is generated, the process that controls the writing of log content is awakened.

[0216] In this embodiment, the buffer for reading log data from the circular buffer and writing the log content to the target log file or system log includes:

[0217] Get the number of memory pages in bytes used to store the log content in the buffer of the target log file or system log, and set the number of bytes in the circular buffer to be equal to the number of memory pages.

[0218] When writing log entries from the circular buffer to the buffer, read a single log entry from the circular buffer, obtain the number of bytes in a single log entry, obtain the remaining space in the buffer, and compare the number of bytes in the log entry with the remaining space.

[0219] When the remaining space is greater than or equal to the number of entries in bytes, it is determined that the buffer can hold a single log entry, the single log entry is written to the buffer and the current position of the single log entry is updated;

[0220] If the remaining space is less than the number of bytes for an entry, and it is determined that the buffer cannot hold a single log entry, the buffer is refreshed, the remaining space in the buffer is retrieved again, and the number of bytes for an entry is compared with the remaining space.

[0221] In this embodiment, the buffer for reading log data from the circular buffer and writing the log content to the target log file or system log further includes:

[0222] When the remaining space is greater than or equal to the number of bytes in the circular buffer, read multiple log data entries equal to the number of bytes in the circular buffer and write these multiple log data entries into the buffer in batches.

[0223] After writing multiple log data entries to the buffer in batches, the buffer is flushed to determine if there is any remaining log data.

[0224] If there is remaining log data in the circular buffer, continue reading multiple log data entries from the circular buffer; otherwise, terminate the process after flushing the buffer.

[0225] In this embodiment, the buffer for reading log data from the circular buffer and writing the log content to the target log file or system log further includes:

[0226] When reading the first log entry from the circular buffer, determine whether the first log entry is an entry that was truncated when the previous memory page of the buffer was full;

[0227] If the first log entry is a truncated entry when the previous memory page of the buffer is full, then the first log entry will be written separately into the buffer to avoid log formatting errors.

[0228] In this embodiment, obtaining the remaining space of the buffer includes:

[0229] Set the write pointer to indicate the end of the stored data in the buffer;

[0230] Get the position of the write pointer in the buffer. Before the write pointer is the stored data in the buffer, and after the write pointer is the remaining space in the buffer.

[0231] In this embodiment, the method further includes:

[0232] The buffer is flushed when the memory page preceding it is full.

[0233] After writing multiple log data entries (number of bytes) to the circular buffer in batches, flush the buffer.

[0234] When the target log is recorded to the target log file pointed to by the target log path or after the system log is switched, the buffer is refreshed;

[0235] When a kernel module exits, the buffer is flushed.

[0236] In this embodiment, the generated logs are formatted and timestamps are added to form log data, including:

[0237] Get the microsecond-level time of the generated logs, convert the microsecond-level time to the local millisecond-level time, convert the local millisecond-level time to structured time, and extract the month, date, hour, minute, and second information;

[0238] The extracted month, date, hour, minute, and second information are used to form a timestamp using a preset time format. When there is missing time information, a placeholder is used to replace it.

[0239] Combine timestamps with log content, perform format validation on the timestamps, and output the results.

[0240] In this embodiment, the resource release management module 6 is used for:

[0241] When a kernel module is unloaded, all resources are traversed through the context pointer, and resources are released in the following order: stop the work queue service, release buffered data, close files, destroy the ring buffer, and release the context.

[0242] In the aforementioned kernel module log redirection device, intelligent management of the log output path is achieved by setting a log file path interface in the kernel module and dynamically determining whether the log content contains a valid file path throughout the entire process of log generation, parsing, and writing. When a valid file path is detected in the log content, the system can automatically configure the target log path in the log file path interface and enable log redirection, so that the log is recorded to the specified target log file; when no valid file path is found in the log content, the log is recorded to the system log by default. This process automatically disables redirection after the log is written, restoring the default output state. This application realizes dynamic configurability and automatic switching of the log output path, avoiding the log coupling problem caused by the strong binding between the log recording path and the system log in traditional kernel modules; at the same time, since log redirection is only enabled when needed and automatically released after recording is completed, system resource consumption and file handle conflicts are reduced, significantly improving the reliability of log management; in addition, by directly completing log path parsing and redirection control within the kernel module, frequent user-mode intervention or complex configuration operations are avoided, thereby improving log processing efficiency and overall system performance. Therefore, this method achieves isolated, highly reliable, and high-performance management of kernel module logs.

[0243] For a description of the features in the embodiment corresponding to the kernel module log redirection device, please refer to the relevant description of the embodiment corresponding to the kernel module log redirection method, which will not be repeated here.

[0244] Embodiments of this application also provide an electronic device, including a memory and a processor, wherein the memory stores a computer program, and the processor is configured to run the computer program to perform the steps in any of the kernel module log redirection method embodiments described above.

[0245] In one embodiment, the electronic device may be a server, and its internal structure diagram may be as follows: Figure 11As shown, this electronic device includes a processor, memory, network interface, and database connected via a system bus. The processor provides computing and control capabilities. The memory includes a non-volatile storage medium and internal memory. The non-volatile storage medium stores the operating system, computer programs, and the database. The internal memory provides an environment for the operation of the operating system and computer programs stored in the non-volatile storage medium. The database stores kernel module log redirection data. The network interface communicates with external terminals via a network connection. When executed by the processor, the computer program implements a kernel module log redirection method.

[0246] Embodiments of this application also provide a computer-readable storage medium storing a computer program, wherein the computer program is configured to execute the steps in any of the above-described kernel module log redirection method embodiments at runtime:

[0247] In response to the generation of logs, determine whether to write a valid file path in the log content for each log entry based on its log type;

[0248] When the kernel module receives the target log, it parses the log content of the target log and determines whether there is a valid file path in the log content;

[0249] If a valid file path exists in the log content of the target log, then the target log path is configured in the log file path interface according to the valid file path, log redirection is enabled, the target log is recorded to the target log file pointed to by the target log path, and log redirection is disabled by setting the log file path interface to empty.

[0250] If a valid file path does not exist in the log content of the target log, the log file path interface will not enable log redirection and the target log will be recorded in the system log.

[0251] In one exemplary embodiment, the aforementioned computer-readable storage medium may include, but is not limited to, various media capable of storing computer programs, such as a USB flash drive, read-only memory (ROM), random access memory (RAM), portable hard disk, magnetic disk, or optical disk.

[0252] Embodiments of this application also provide a computer program product, which includes a computer program that, when executed by a processor, implements the steps in any of the above-described kernel module log redirection method embodiments:

[0253] In response to the generation of logs, determine whether to write a valid file path in the log content for each log entry based on its log type;

[0254] When the kernel module receives the target log, it parses the log content of the target log and determines whether there is a valid file path in the log content;

[0255] If a valid file path exists in the log content of the target log, then the target log path is configured in the log file path interface according to the valid file path, log redirection is enabled, the target log is recorded to the target log file pointed to by the target log path, and log redirection is disabled by setting the log file path interface to empty.

[0256] If a valid file path does not exist in the log content of the target log, the log file path interface will not enable log redirection and the target log will be recorded in the system log.

[0257] Embodiments of this application also provide another computer program product, including a non-volatile computer-readable storage medium storing a computer program, which, when executed by a processor, implements the steps in any of the above-described kernel module log redirection method embodiments:

[0258] In response to the generation of logs, determine whether to write a valid file path in the log content for each log entry based on its log type;

[0259] When the kernel module receives the target log, it parses the log content of the target log and determines whether there is a valid file path in the log content;

[0260] If a valid file path exists in the log content of the target log, then the target log path is configured in the log file path interface according to the valid file path, log redirection is enabled, the target log is recorded to the target log file pointed to by the target log path, and log redirection is disabled by setting the log file path interface to empty.

[0261] If a valid file path does not exist in the log content of the target log, the log file path interface will not enable log redirection and the target log will be recorded in the system log.

[0262] Those skilled in the art will further recognize that the units and algorithm steps of the various examples described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, computer software, or a combination of both. To clearly illustrate the interchangeability of hardware and software, the components and steps of the various examples have been generally described in terms of functionality in the foregoing description. Whether these functions are implemented in hardware or software depends on the specific application and design constraints of the technical solution. Those skilled in the art can use different methods to implement the described functions for each specific application, but such implementation should not be considered beyond the scope of this application.

[0263] The foregoing has provided a detailed description of a kernel module log redirection method, electronic device, storage medium, and product provided in this application. Specific examples have been used to illustrate the principles and implementation methods of this application. The descriptions of the embodiments above are only intended to help understand the method and core ideas of this application. It should be noted that those skilled in the art can make various improvements and modifications to this application without departing from its principles, and these improvements and modifications also fall within the protection scope of this application.

Claims

1. A kernel module log redirection method, characterized in that, The method includes: When a log is generated, determine whether to write a valid file path in the log content for each log entry based on its log type; When the kernel module receives the target log, it parses the log content of the target log and determines whether there is a valid file path in the log content; If a valid file path exists in the log content of the target log, then the target log path is configured in the log file path interface according to the valid file path, log redirection is enabled, the target log is recorded to the target log file pointed to by the target log path, and log redirection is disabled by setting the log file path interface to empty. If a valid file path does not exist in the log content of the target log, the log file path interface will not enable log redirection and the target log will be recorded in the system log.

2. The kernel module log redirection method according to claim 1, characterized in that, If a valid file path exists in the log content of the target log, then the target log path is configured through the log file path interface according to the valid file path, and log redirection is enabled, including: After receiving the valid file path at the log file path interface, the length of the valid file path and the writability of the file pointed to by the valid file path are verified. If the length of the valid file path is acceptable and the file pointed to by the valid file path is writable, the verification is deemed to have passed; otherwise, the verification is deemed to have failed. If the verification passes, the path and file pointer in the log context are updated, triggering redirection to begin; In response to verification failure, the state of the path and file pointer in the log context remains unchanged, and an error log is output.

3. The kernel module log redirection method according to claim 1, characterized in that, When log redirection is enabled, the following are also included: Determine whether the log file path interface has been configured with an old target log path; If the log file path interface has an old target log path configured, configure a new target log path through the log file path interface, close the old target log file pointed to by the old target log path, update relevant resources, and redirect the logs to the new target log file pointed to by the new target log path. If the log file path interface is not configured with an old target log path, the target log path is configured according to the valid file path through the log file path interface, and the log is redirected to the target log file pointed to by the target log path.

4. The kernel module log redirection method according to claim 1, characterized in that, The method further includes: The generated logs are formatted and timestamps are added to form log data. Write the log data into a circular buffer; When recording the target log to the target log file pointed to by the target log path or the system log, the interrupt of the log content writing process is enabled based on the kernel work queue control, and log data is read from the circular buffer and the log content is written to the buffer of the target log file or the system log.

5. The kernel module log redirection method according to claim 4, characterized in that, The interrupt enablement for the process writing kernel work queue control log content includes: When the remaining space in the buffer is less than the first threshold, blocking and waiting are implemented through a waiting queue. When there is no data in the buffer, the log writing process is put into sleep mode, and the log writing process is woken up when a new log is generated.

6. The kernel module log redirection method according to claim 4, characterized in that, The buffer for reading log data from the circular buffer and writing the log content to the target log file or the system log includes: Obtain the number of memory pages in bytes used by the buffer of the target log file or the system log to store the log content, and set the number of bytes in the circular buffer to be equal to the number of memory pages in bytes; When writing log entries from the circular buffer into the buffer, read a single log entry from the circular buffer, obtain the number of bytes in the single log entry, obtain the remaining space in the buffer, and compare the number of bytes in the entry with the remaining space. When the remaining space is greater than or equal to the number of bytes of the entry, it is determined that the buffer can accommodate the single log data, the single log data is written into the buffer and the current position of the single log is updated; If the remaining space is less than the number of bytes of the entry, and it is determined that the buffer cannot accommodate the single log data, then the buffer is refreshed, the remaining space of the buffer is obtained again, and the number of bytes of the entry is compared with the remaining space again.

7. The kernel module log redirection method according to claim 6, characterized in that, The buffer for reading log data from the circular buffer and writing the log content to the target log file or the system log further includes: When the remaining space is greater than or equal to the number of bytes in the circular buffer, multiple log data entries equal to the number of bytes in the circular buffer are read and written into the buffer in batches. In response to writing the multiple log data entries into the buffer in batches, the buffer is refreshed to determine whether there is any remaining log data. If there is remaining log data in the circular buffer, then continue reading multiple log data entries from the circular buffer; otherwise, trigger a refresh of the buffer and end the process.

8. The kernel module log redirection method according to claim 7, characterized in that, The buffer for reading log data from the circular buffer and writing the log content to the target log file or the system log further includes: When reading the first log data from the circular buffer, determine whether the first log data is an entry that was truncated when the previous memory page of the buffer was full; If the first log entry is a truncated entry when the previous memory page of the buffer is full, then the first log entry is written separately into the buffer to avoid log format corruption.

9. The kernel module log redirection method according to claim 6, characterized in that, The step of obtaining the remaining space of the buffer includes: Set the write pointer to indicate the end of the stored data in the buffer; Obtain the position of the write pointer within the buffer. The data stored in the buffer is before the write pointer, and the remaining space in the buffer is after the write pointer.

10. The kernel module log redirection method according to claim 4, characterized in that, The method further includes: When the memory page preceding the buffer is full, the buffer is flushed. After writing multiple log data entries, each corresponding to the number of bytes in the circular buffer, into the buffer, the buffer is refreshed. The buffer is refreshed after the target log is recorded to the target log file pointed to by the target log path or after the system log is switched. When the kernel module exits, the buffer is flushed.

11. The kernel module log redirection method according to claim 4, characterized in that, The process of formatting and adding timestamps to the generated logs to form log data includes: Obtain the microsecond-level time of the generated logs, convert the microsecond-level time into millisecond-level local time, convert the millisecond-level local time into structured time, and extract the month, date, hour, minute, and second information; The extracted month, date, hour, minute, and second information are used to form a timestamp using a preset time format. When there is missing time information, a placeholder is used to replace it. The timestamp and log content are concatenated, and the timestamp is format-validated and output.

12. The kernel module log redirection method according to claim 1, characterized in that, The method further includes: When the kernel module is unloaded, all resources are traversed through the context pointer, and resources are released in the following order: stop work queue service, release buffered data, close files, destroy the ring buffer, and release the context.

13. An electronic device, characterized in that, include: Memory, used to store computer programs; A processor, configured to implement the kernel module log redirection method as described in any one of claims 1 to 12 when executing the computer program.

14. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program, wherein when the computer program is executed by a processor, it implements the steps of the kernel module log redirection method as described in any one of claims 1 to 12.

15. A computer program product, comprising a computer program, characterized in that, When the computer program is executed by the processor, it implements the steps of the kernel module log redirection method as described in any one of claims 1 to 12.

Citation Information

Patent Citations

  • Log collection method and device

    CN108170578A

  • Log storage method, device and equipment and readable storage medium

    CN116561091A