printk
- C course
- Expert
- Lesson 9/47
- 5 min
Learn kernel logging with printk.
What is printk?
printk is the printing function used inside the kernel. It works like printf but writes to the kernel log buffer, not the screen.
Each message takes a priority prefix: KERN_EMERG, KERN_ALERT, KERN_CRIT, KERN_ERR, KERN_WARNING, KERN_NOTICE, KERN_INFO, KERN_DEBUG. The prefix controls which console level shows the message. You read these messages with dmesg. Driver authors use the printk(KERN_INFO "...\n") form.
Log levels and usage
printk's eight levels are numbered: KERN_EMERG is 0, KERN_DEBUG is 7. Low numbers mean high priority. Driver authors pick the level to match the situation.
Use KERN_INFO for information, KERN_ERR for errors, KERN_DEBUG for debugging. KERN_DEBUG messages are hidden by default on production kernels. Too many logs fill the buffer and push out important messages, so authors give each message the lowest priority it needs. pr_info and pr_err are short wrappers.
Practice Print log levels
Define void print_loglevel(const char *name, int level) with body printf("%d:%s\n", level, name);. In main call it for four levels: ("KERN_EMERG", 0), ("KERN_ALERT", 1), ("KERN_ERR", 3), ("KERN_INFO", 6).
Starter code
#include <stdio.h>
// Define print_loglevel function
// Call it for KERN_EMERG, KERN_ALERT, KERN_ERR, KERN_INFO
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
void print_loglevel(const char *name, int level) {
printf("%d:%s\n", level, name);
}
int main(void) {
print_loglevel("KERN_EMERG", 0);
print_loglevel("KERN_ALERT", 1);
print_loglevel("KERN_ERR", 3);
print_loglevel("KERN_INFO", 6);
return 0;
}Expected output
0:KERN_EMERG 1:KERN_ALERT 3:KERN_ERR 6:KERN_INFO
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the printk level prefix
printk(KERN_____ "driver loaded
");
printk(KERN_ALERT "driver loaded
");
Explanation: KERN_ALERT tags messages requiring immediate action.
2 Match log levels to values
| Term | Meaning |
|---|---|
KERN_EMERG |
0 |
KERN_ALERT |
1 |
KERN_ERR |
3 |
KERN_INFO |
6 |
3 Which is the highest-priority log level?
- KERN_EMERG Correct answer
- KERN_INFO
- KERN_DEBUG
- KERN_WARNING
Explanation: KERN_EMERG means system crash, the highest priority.