aboutsummaryrefslogtreecommitdiffstats
path: root/examples/print-tty.c
blob: 742e1036254050d2dbd8180a83787ea46bcb1d3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* ==========================================================================
    Licensed under BSD 2clause license See LICENSE file for more information
    Author: Michał Łyszczek <michal.lyszczek@bofc.pl>
   ========================================================================== */

#include "embedlog.h"

#if HAVE_CONFIG_H
#   include "config.h"
#endif

#if HAVE_TERMIOS_H
#   include <termios.h>
#endif

#ifdef EMBEDLOG_DEMO_LIBRARY
int el_demo_print_tty_main(int argc, const char *argv[])
#else
int main(int argc, const char *argv[])
#endif
{
	/* first we nned to initialize logger to known state */
	el_init();

	if (argc != 2)
	{
		el_print(ELF, "usage: %s <path-to-serial-device>", argv[0]);
		return 1;
	}

	/* to use logger you need to enable at least one output,
	 * without it logs will be printed to /dev/null. Here we set
	 * output to serial device. */
	el_option(EL_OUT, EL_OUT_TTY);

#if HAVE_TERMIOS_H
	/* enbaling tty output is not enough, we still need to
	 * configure which device we want to use and at what speed.
	 * Transmission parameters are 8N1 by default. Baudrate should
	 * be taken from termios (3). */
	if (el_option(EL_TTY_DEV, argv[1], B9600) != 0)
#else
	/* if termios is not available on your system, you can specify
	 * 0 as baund rate, this will tell embedlog not to configure
	 * serial port and use it as is - ie. it can be configured
	 * at system startup or even during compile time */
	if (el_option(EL_TTY_DEV, argv[1], 0) != 0)
#endif
	{
		perror("tty set failed");
		el_cleanup();
		return 1;
	}

	/* now we can simply print messages like we would do it with
	 * ordinary printf - we just need to log level macro as a first
	 * argument */
	el_print(ELI, "Info message");
	el_print(ELF, "Fatal message with additional argument %d", 42);
	el_print(ELD, "Debug message that won't be printed due to log level");

	/* we can change log level in runtime as we see fit, now enable
	 * debug prints */
	el_option(EL_LEVEL, EL_DBG);
	el_print(ELD, "But now debug will be printed");

	/* altough embedlog does not use dynamic allocation by itself,
	 * system may allocate some resources (like opened file
	 * descriptors when printing to file), with el_cleanup, we can
	 * make sure all resources are freed. In this example, this
	 * function will close opened tty file descriptor.  */
	el_cleanup();

	return 0;
}