← Documents Documentation/core-api/printk-basics.rst GitHub 원문 ↗

Linux 6.18.37 · Core API

printk를 이용한 메시지 기록

printk 로그 수준, 커널 ring buffer, console_loglevel 조정, pr_* 별칭과 pr_fmt 및 조건부 디버그 매크로를 설명합니다.

Source pathDocumentation/core-api/printk-basics.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

printk-basics.rst:1-112

`printk()`는 커널 메시지를 `/dev/kmsg`로 공개되는 ring buffer에 기록하는 기본 로깅 함수입니다. 메시지에는 `KERN_EMERG`부터 `KERN_DEBUG`까지 중요도를 나타내는 log level을 붙일 수 있습니다.

현재 콘솔에 즉시 표시할지는 메시지 우선순위와 `console_loglevel` 비교로 결정합니다. `/proc/sys/kernel/printk` 또는 `dmesg -n`으로 임계값을 확인하고 변경할 수 있으며, level을 생략하면 `KERN_DEFAULT`가 적용됩니다.

실제 코드에서는 level이 이름에 포함된 `pr_info()`, `pr_warn()` 같은 `pr_*()` 매크로가 간결합니다. `pr_fmt()`로 파일 공통 접두사를 정의할 수 있고, `pr_debug()`와 `pr_devel()`은 빌드 설정에 따라 제거되는 조건부 디버그 호출입니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 ===========================
4 Message logging with printk
5 ===========================
6
7 printk() is one of the most widely known functions in the Linux kernel. It's the
8 standard tool we have for printing messages and usually the most basic way of
9 tracing and debugging. If you're familiar with printf(3) you can tell printk()
10 is based on it, although it has some functional differences:
11
12 - printk() messages can specify a log level.
13
14 - the format string, while largely compatible with C99, doesn't follow the
15 exact same specification. It has some extensions and a few limitations
16 (no ``%n`` or floating point conversion specifiers). See :ref:`How to get
17 printk format specifiers right <printk-specifiers>`.
18
19 All printk() messages are printed to the kernel log buffer, which is a ring
20 buffer exported to userspace through /dev/kmsg. The usual way to read it is
21 using ``dmesg``.
22
23 printk() is typically used like this::
24
25 printk(KERN_INFO "Message: %s\n", arg);
26
27 where ``KERN_INFO`` is the log level (note that it's concatenated to the format
28 string, the log level is not a separate argument). The available log levels are:
29
30 +----------------+--------+-----------------------------------------------+
31 | Name | String | Alias function |
32 +================+========+===============================================+
33 | KERN_EMERG | "0" | pr_emerg() |
34 +----------------+--------+-----------------------------------------------+
35 | KERN_ALERT | "1" | pr_alert() |
36 +----------------+--------+-----------------------------------------------+
37 | KERN_CRIT | "2" | pr_crit() |
38 +----------------+--------+-----------------------------------------------+
39 | KERN_ERR | "3" | pr_err() |
40 +----------------+--------+-----------------------------------------------+
41 | KERN_WARNING | "4" | pr_warn() |
42 +----------------+--------+-----------------------------------------------+
43 | KERN_NOTICE | "5" | pr_notice() |
44 +----------------+--------+-----------------------------------------------+
45 | KERN_INFO | "6" | pr_info() |
46 +----------------+--------+-----------------------------------------------+
47 | KERN_DEBUG | "7" | pr_debug() and pr_devel() if DEBUG is defined |
48 +----------------+--------+-----------------------------------------------+
49 | KERN_DEFAULT | "" | |
50 +----------------+--------+-----------------------------------------------+
51 | KERN_CONT | "c" | pr_cont() |
52 +----------------+--------+-----------------------------------------------+
53
54
55 The log level specifies the importance of a message. The kernel decides whether
56 to show the message immediately (printing it to the current console) depending
57 on its log level and the current *console_loglevel* (a kernel variable). If the
58 message priority is higher (lower log level value) than the *console_loglevel*
59 the message will be printed to the console.
60
61 If the log level is omitted, the message is printed with ``KERN_DEFAULT``
62 level.
63
64 You can check the current *console_loglevel* with::
65
66 $ cat /proc/sys/kernel/printk
67 4 4 1 7
68
69 The result shows the *current*, *default*, *minimum* and *boot-time-default* log
70 levels.
71
72 To change the current console_loglevel simply write the desired level to
73 ``/proc/sys/kernel/printk``. For example, to print all messages to the console::
74
75 # echo 8 > /proc/sys/kernel/printk
76
77 Another way, using ``dmesg``::
78
79 # dmesg -n 5
80
81 sets the console_loglevel to print KERN_WARNING (4) or more severe messages to
82 console. See ``dmesg(1)`` for more information.
83
84 As an alternative to printk() you can use the ``pr_*()`` aliases for
85 logging. This family of macros embed the log level in the macro names. For
86 example::
87
88 pr_info("Info message no. %d\n", msg_num);
89
90 prints a ``KERN_INFO`` message.
91
92 Besides being more concise than the equivalent printk() calls, they can use a
93 common definition for the format string through the pr_fmt() macro. For
94 instance, defining this at the top of a source file (before any ``#include``
95 directive)::
96
97 #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__
98
99 would prefix every pr_*() message in that file with the module and function name
100 that originated the message.
101
102 For debugging purposes there are also two conditionally-compiled macros:
103 pr_debug() and pr_devel(), which are compiled-out unless ``DEBUG`` (or
104 also ``CONFIG_DYNAMIC_DEBUG`` in the case of pr_debug()) is defined.
105
106
107 Function reference
108 ==================
109
110 .. kernel-doc:: include/linux/printk.h
111 :functions: printk pr_emerg pr_alert pr_crit pr_err pr_warn pr_notice pr_info
112 pr_fmt pr_debug pr_devel pr_cont
113

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

printk를 이용한 메시지 기록

1-21

SPDX 라이선스 식별자는 GPL-2.0입니다.

`printk`를 이용한 메시지 기록

`printk()`는 Linux 커널에서 가장 널리 알려진 함수 중 하나입니다. 메시지를 출력하는 표준 도구이며 일반적으로 가장 기본적인 추적 및 디버깅 수단입니다. `printf(3)`에 익숙하다면 `printk()`가 이를 바탕으로 만들어졌음을 알 수 있지만 몇 가지 기능 차이가 있습니다.

  • `printk()` 메시지에는 log level을 지정할 수 있습니다.
  • Format string은 대체로 C99와 호환되지만 정확히 같은 명세를 따르지는 않습니다. 몇 가지 확장과 제한이 있으며 `%n` 및 부동소수점 변환 지정자는 지원하지 않습니다. 자세한 내용은 `printk-specifiers` 참조인 'How to get printk format specifiers right'를 확인하십시오.

모든 `printk()` 메시지는 커널 log buffer에 기록됩니다. 이 버퍼는 `/dev/kmsg`를 통해 사용자 공간에 공개되는 ring buffer이며, 일반적으로 `dmesg` 명령으로 읽습니다.

기본 호출 형식

22-28

`printk()`는 일반적으로 다음과 같이 사용합니다.

printk(KERN_INFO "Message: %s\n", arg);

`KERN_INFO`는 log level입니다. 별도 인자가 아니라 format string과 이어 붙인다는 점에 유의해야 합니다. 사용할 수 있는 log level은 다음 표와 같습니다.

로그 수준과 콘솔 출력

29-62
이름문자열별칭 함수
KERN_EMERG"0"pr_emerg()
KERN_ALERT"1"pr_alert()
KERN_CRIT"2"pr_crit()
KERN_ERR"3"pr_err()
KERN_WARNING"4"pr_warn()
KERN_NOTICE"5"pr_notice()
KERN_INFO"6"pr_info()
KERN_DEBUG"7"DEBUG가 정의되면 pr_debug() 및 pr_devel()
KERN_DEFAULT""
KERN_CONT"c"pr_cont()

Log level은 메시지의 중요도를 나타냅니다. 커널은 메시지의 log level과 현재 커널 변수 `console_loglevel`을 비교하여 현재 콘솔에 즉시 출력할지 결정합니다. 메시지 우선순위가 `console_loglevel`보다 높으면, 즉 log level 숫자가 더 작으면 콘솔에 출력합니다.

Log level을 생략한 메시지는 `KERN_DEFAULT` 수준으로 기록됩니다.

console_loglevel 확인과 변경

63-82

현재 `console_loglevel`은 다음 명령으로 확인할 수 있습니다.

$ cat /proc/sys/kernel/printk
4        4        1        7

결과는 차례대로 현재(current), 기본(default), 최솟값(minimum), 부팅 시 기본값(boot-time-default) log level을 보여 줍니다.

현재 `console_loglevel`을 바꾸려면 원하는 값을 `/proc/sys/kernel/printk`에 쓰면 됩니다. 예를 들어 모든 메시지를 콘솔에 출력하려면 다음과 같이 실행합니다.

# echo 8 > /proc/sys/kernel/printk

`dmesg`를 사용하는 다른 방법도 있습니다.

# dmesg -n 5

이 명령은 `KERN_WARNING`(4) 이상으로 심각한 메시지를 콘솔에 출력하도록 `console_loglevel`을 설정합니다. 자세한 내용은 `dmesg(1)`을 참조하십시오.

pr_*() 별칭과 pr_fmt()

83-100

`printk()` 대신 로깅용 `pr_*()` 별칭을 사용할 수 있습니다. 이 매크로군은 이름 자체에 log level을 포함합니다. 예는 다음과 같습니다.

pr_info("Info message no. %d\n", msg_num);

이 호출은 `KERN_INFO` 메시지를 출력합니다.

`pr_*()` 매크로는 같은 의미의 `printk()` 호출보다 간결할 뿐 아니라 `pr_fmt()` 매크로를 통해 공통 format string 정의를 사용할 수 있습니다. 예를 들어 소스 파일의 모든 `#include` 지시자보다 앞에 다음을 정의할 수 있습니다.

#define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__

그러면 해당 파일의 모든 `pr_*()` 메시지 앞에 메시지를 발생시킨 모듈 이름과 함수 이름이 붙습니다.

조건부 디버그 매크로

101-106

디버깅을 위해 조건부로 컴파일되는 `pr_debug()`와 `pr_devel()` 매크로도 있습니다. `DEBUG`가 정의되지 않으면 이 호출들은 컴파일 과정에서 제거됩니다. `pr_debug()`의 경우에는 `CONFIG_DYNAMIC_DEBUG`가 정의되어 있어도 사용할 수 있습니다.

함수 참조

107-112

함수 참조 (Function reference)

함수 문서는 `include/linux/printk.h`의 kernel-doc에서 추출합니다. 대상은 `printk`, `pr_emerg`, `pr_alert`, `pr_crit`, `pr_err`, `pr_warn`, `pr_notice`, `pr_info`, `pr_fmt`, `pr_debug`, `pr_devel`, `pr_cont`입니다.