1/*
2 *	Driver for USB Audio Device Class devices.
3 *	Copyright (c) 2009,10,12 S.Zharski <imker@gmx.li>
4 *	Distributed under the terms of the MIT license.
5 *
6 */
7
8#include <lock.h> // for mutex
9#include <stdlib.h> // for file operation
10#include <string.h> // for file operation
11#include <stdio.h> // for file operation
12
13#include "Settings.h"
14
15bool gTraceOn = false;
16bool gTruncateLogFile = false;
17bool gAddTimeStamp = true;
18bool gTraceFlow = false;
19static char *gLogFilePath = NULL;
20mutex gLogLock;
21
22static
23void create_log()
24{
25	if (gLogFilePath == NULL)
26		return;
27
28	int flags = O_WRONLY | O_CREAT | ((gTruncateLogFile) ? O_TRUNC : 0);
29	int fd = open(gLogFilePath, flags, 0666);
30	if (fd >= 0)
31		close(fd);
32
33	mutex_init(&gLogLock, DRIVER_NAME"-logging");
34}
35
36
37void load_settings()
38{
39	void *handle = load_driver_settings(DRIVER_NAME);
40	if (handle == 0)
41		return;
42
43	gTraceOn = get_driver_boolean_parameter(handle, "trace", gTraceOn, true);
44	gTraceFlow = get_driver_boolean_parameter(handle, "trace_flow",
45						gTraceFlow, true);
46	gTruncateLogFile = get_driver_boolean_parameter(handle,	"truncate_logfile",
47						gTruncateLogFile, true);
48	gAddTimeStamp = get_driver_boolean_parameter(handle, "add_timestamp",
49						gAddTimeStamp, true);
50	const char * logFilePath = get_driver_parameter(handle, "logfile",
51						NULL, "/var/log/"DRIVER_NAME".log");
52	if (logFilePath != NULL) {
53		gLogFilePath = strdup(logFilePath);
54	}
55
56	unload_driver_settings(handle);
57
58	create_log();
59}
60
61
62void release_settings()
63{
64	if (gLogFilePath != NULL) {
65		mutex_destroy(&gLogLock);
66		free(gLogFilePath);
67	}
68}
69
70
71void usb_audio_trace(bool force, const char* func, const char *fmt, ...)
72{
73	if (!(force || gTraceOn)) {
74		return;
75	}
76
77	va_list arg_list;
78	static const char *prefix = DRIVER_NAME":";
79	static char buffer[1024];
80	char *buf_ptr = buffer;
81	if (gLogFilePath == NULL) {
82		strlcpy(buffer, prefix, sizeof(buffer));
83		buf_ptr += strlen(prefix);
84	}
85
86	if (gAddTimeStamp) {
87		bigtime_t time = system_time();
88		uint32 msec = time / 1000;
89		uint32 sec = msec / 1000;
90		sprintf(buf_ptr, "%02ld.%02ld.%03ld:",
91				sec / 60, sec % 60, msec % 1000);
92		buf_ptr += strlen(buf_ptr);
93	}
94
95	if (func	!= NULL) {
96		sprintf(buf_ptr, "%s::", func);
97		buf_ptr += strlen(buf_ptr);
98	}
99
100	va_start(arg_list, fmt);
101	vsprintf(buf_ptr, fmt, arg_list);
102	va_end(arg_list);
103
104	if (gLogFilePath == NULL) {
105		dprintf(buffer);
106		return;
107	}
108
109	mutex_lock(&gLogLock);
110	int fd = open(gLogFilePath, O_WRONLY | O_APPEND);
111	if (fd >= 0) {
112		write(fd, buffer, strlen(buffer));
113		close(fd);
114	}
115	mutex_unlock(&gLogLock);
116}
117
118