Log.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /*******************************************************************************
  2. * Copyright (c) 2009, 2018 IBM Corp.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * http://www.eclipse.org/legal/epl-v10.html
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Ian Craggs - initial API and implementation and/or initial documentation
  15. * Ian Craggs - updates for the async client
  16. * Ian Craggs - fix for bug #427028
  17. *******************************************************************************/
  18. /**
  19. * @file
  20. * \brief Logging and tracing module
  21. *
  22. *
  23. */
  24. #include "Log.h"
  25. #include "MQTTPacket.h"
  26. #include "MQTTProtocol.h"
  27. #include "MQTTProtocolClient.h"
  28. #include "Messages.h"
  29. #include "LinkedList.h"
  30. #include "StackTrace.h"
  31. #include "Thread.h"
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <stdarg.h>
  35. #include <time.h>
  36. #include <string.h>
  37. #if !defined(WIN32) && !defined(WIN64)
  38. #include <syslog.h>
  39. #include <sys/stat.h>
  40. #define GETTIMEOFDAY 1
  41. #else
  42. #define snprintf _snprintf
  43. #endif
  44. #if defined(GETTIMEOFDAY)
  45. #include <sys/time.h>
  46. #else
  47. #include <sys/timeb.h>
  48. #endif
  49. #if !defined(WIN32) && !defined(WIN64)
  50. /**
  51. * _unlink mapping for linux
  52. */
  53. #define _unlink unlink
  54. #endif
  55. #if !defined(min)
  56. #define min(A,B) ( (A) < (B) ? (A):(B))
  57. #endif
  58. trace_settings_type trace_settings =
  59. {
  60. TRACE_MINIMUM,
  61. 400,
  62. INVALID_LEVEL
  63. };
  64. #define MAX_FUNCTION_NAME_LENGTH 256
  65. typedef struct
  66. {
  67. #if defined(GETTIMEOFDAY)
  68. struct timeval ts;
  69. #else
  70. struct timeb ts;
  71. #endif
  72. int sametime_count;
  73. int number;
  74. int thread_id;
  75. int depth;
  76. char name[MAX_FUNCTION_NAME_LENGTH + 1];
  77. int line;
  78. int has_rc;
  79. int rc;
  80. enum LOG_LEVELS level;
  81. } traceEntry;
  82. static int start_index = -1,
  83. next_index = 0;
  84. static traceEntry* trace_queue = NULL;
  85. static int trace_queue_size = 0;
  86. static FILE* trace_destination = NULL; /**< flag to indicate if trace is to be sent to a stream */
  87. static char* trace_destination_name = NULL; /**< the name of the trace file */
  88. static char* trace_destination_backup_name = NULL; /**< the name of the backup trace file */
  89. static int lines_written = 0; /**< number of lines written to the current output file */
  90. static int max_lines_per_file = 1000; /**< maximum number of lines to write to one trace file */
  91. static enum LOG_LEVELS trace_output_level = INVALID_LEVEL;
  92. static Log_traceCallback* trace_callback = NULL;
  93. static traceEntry* Log_pretrace(void);
  94. static char* Log_formatTraceEntry(traceEntry* cur_entry);
  95. static void Log_output(enum LOG_LEVELS log_level, const char *msg);
  96. static void Log_posttrace(enum LOG_LEVELS log_level, traceEntry* cur_entry);
  97. static void Log_trace(enum LOG_LEVELS log_level, const char *buf);
  98. #if 0
  99. static FILE* Log_destToFile(const char *dest);
  100. static int Log_compareEntries(const char *entry1, const char *entry2);
  101. #endif
  102. static int sametime_count = 0;
  103. #if defined(GETTIMEOFDAY)
  104. struct timeval ts, last_ts;
  105. #else
  106. struct timeb ts, last_ts;
  107. #endif
  108. static char msg_buf[512];
  109. #if defined(WIN32) || defined(WIN64)
  110. mutex_type log_mutex;
  111. #else
  112. static pthread_mutex_t log_mutex_store = PTHREAD_MUTEX_INITIALIZER;
  113. static mutex_type log_mutex = &log_mutex_store;
  114. #endif
  115. int Log_initialize(Log_nameValue* info)
  116. {
  117. int rc = -1;
  118. char* envval = NULL;
  119. #if !defined(WIN32) && !defined(WIN64)
  120. struct stat buf;
  121. #endif
  122. if ((trace_queue = malloc(sizeof(traceEntry) * trace_settings.max_trace_entries)) == NULL)
  123. return rc;
  124. trace_queue_size = trace_settings.max_trace_entries;
  125. if ((envval = getenv("MQTT_C_CLIENT_TRACE")) != NULL && strlen(envval) > 0)
  126. {
  127. if (strcmp(envval, "ON") == 0 || (trace_destination = fopen(envval, "w")) == NULL)
  128. trace_destination = stdout;
  129. else
  130. {
  131. trace_destination_name = malloc(strlen(envval) + 1);
  132. strcpy(trace_destination_name, envval);
  133. trace_destination_backup_name = malloc(strlen(envval) + 3);
  134. sprintf(trace_destination_backup_name, "%s.0", trace_destination_name);
  135. }
  136. }
  137. if ((envval = getenv("MQTT_C_CLIENT_TRACE_MAX_LINES")) != NULL && strlen(envval) > 0)
  138. {
  139. max_lines_per_file = atoi(envval);
  140. if (max_lines_per_file <= 0)
  141. max_lines_per_file = 1000;
  142. }
  143. if ((envval = getenv("MQTT_C_CLIENT_TRACE_LEVEL")) != NULL && strlen(envval) > 0)
  144. {
  145. if (strcmp(envval, "MAXIMUM") == 0 || strcmp(envval, "TRACE_MAXIMUM") == 0)
  146. trace_settings.trace_level = TRACE_MAXIMUM;
  147. else if (strcmp(envval, "MEDIUM") == 0 || strcmp(envval, "TRACE_MEDIUM") == 0)
  148. trace_settings.trace_level = TRACE_MEDIUM;
  149. else if (strcmp(envval, "MINIMUM") == 0 || strcmp(envval, "TRACE_MINIMUM") == 0)
  150. trace_settings.trace_level = TRACE_MINIMUM;
  151. else if (strcmp(envval, "PROTOCOL") == 0 || strcmp(envval, "TRACE_PROTOCOL") == 0)
  152. trace_output_level = TRACE_PROTOCOL;
  153. else if (strcmp(envval, "ERROR") == 0 || strcmp(envval, "TRACE_ERROR") == 0)
  154. trace_output_level = LOG_ERROR;
  155. }
  156. Log_output(TRACE_MINIMUM, "=========================================================");
  157. Log_output(TRACE_MINIMUM, " Trace Output");
  158. if (info)
  159. {
  160. while (info->name)
  161. {
  162. snprintf(msg_buf, sizeof(msg_buf), "%s: %s", info->name, info->value);
  163. Log_output(TRACE_MINIMUM, msg_buf);
  164. info++;
  165. }
  166. }
  167. #if !defined(WIN32) && !defined(WIN64)
  168. if (stat("/proc/version", &buf) != -1)
  169. {
  170. FILE* vfile;
  171. if ((vfile = fopen("/proc/version", "r")) != NULL)
  172. {
  173. int len;
  174. strcpy(msg_buf, "/proc/version: ");
  175. len = strlen(msg_buf);
  176. if (fgets(&msg_buf[len], sizeof(msg_buf) - len, vfile))
  177. Log_output(TRACE_MINIMUM, msg_buf);
  178. fclose(vfile);
  179. }
  180. }
  181. #endif
  182. Log_output(TRACE_MINIMUM, "=========================================================");
  183. return rc;
  184. }
  185. void Log_setTraceCallback(Log_traceCallback* callback)
  186. {
  187. trace_callback = callback;
  188. }
  189. void Log_setTraceLevel(enum LOG_LEVELS level)
  190. {
  191. if (level < TRACE_MINIMUM) /* the lowest we can go is TRACE_MINIMUM*/
  192. trace_settings.trace_level = level;
  193. trace_output_level = level;
  194. }
  195. void Log_terminate(void)
  196. {
  197. free(trace_queue);
  198. trace_queue = NULL;
  199. trace_queue_size = 0;
  200. if (trace_destination)
  201. {
  202. if (trace_destination != stdout)
  203. fclose(trace_destination);
  204. trace_destination = NULL;
  205. }
  206. if (trace_destination_name) {
  207. free(trace_destination_name);
  208. trace_destination_name = NULL;
  209. }
  210. if (trace_destination_backup_name) {
  211. free(trace_destination_backup_name);
  212. trace_destination_backup_name = NULL;
  213. }
  214. start_index = -1;
  215. next_index = 0;
  216. trace_output_level = INVALID_LEVEL;
  217. sametime_count = 0;
  218. }
  219. static traceEntry* Log_pretrace(void)
  220. {
  221. traceEntry *cur_entry = NULL;
  222. /* calling ftime/gettimeofday seems to be comparatively expensive, so we need to limit its use */
  223. if (++sametime_count % 20 == 0)
  224. {
  225. #if defined(GETTIMEOFDAY)
  226. gettimeofday(&ts, NULL);
  227. if (ts.tv_sec != last_ts.tv_sec || ts.tv_usec != last_ts.tv_usec)
  228. #else
  229. ftime(&ts);
  230. if (ts.time != last_ts.time || ts.millitm != last_ts.millitm)
  231. #endif
  232. {
  233. sametime_count = 0;
  234. last_ts = ts;
  235. }
  236. }
  237. if (trace_queue_size != trace_settings.max_trace_entries)
  238. {
  239. traceEntry* new_trace_queue = malloc(sizeof(traceEntry) * trace_settings.max_trace_entries);
  240. memcpy(new_trace_queue, trace_queue, min(trace_queue_size, trace_settings.max_trace_entries) * sizeof(traceEntry));
  241. free(trace_queue);
  242. trace_queue = new_trace_queue;
  243. trace_queue_size = trace_settings.max_trace_entries;
  244. if (start_index > trace_settings.max_trace_entries + 1 ||
  245. next_index > trace_settings.max_trace_entries + 1)
  246. {
  247. start_index = -1;
  248. next_index = 0;
  249. }
  250. }
  251. /* add to trace buffer */
  252. cur_entry = &trace_queue[next_index];
  253. if (next_index == start_index) /* means the buffer is full */
  254. {
  255. if (++start_index == trace_settings.max_trace_entries)
  256. start_index = 0;
  257. } else if (start_index == -1)
  258. start_index = 0;
  259. if (++next_index == trace_settings.max_trace_entries)
  260. next_index = 0;
  261. return cur_entry;
  262. }
  263. static char* Log_formatTraceEntry(traceEntry* cur_entry)
  264. {
  265. struct tm *timeinfo;
  266. int buf_pos = 31;
  267. #if defined(GETTIMEOFDAY)
  268. timeinfo = localtime((time_t *)&cur_entry->ts.tv_sec);
  269. #else
  270. timeinfo = localtime(&cur_entry->ts.time);
  271. #endif
  272. strftime(&msg_buf[7], 80, "%Y%m%d %H%M%S ", timeinfo);
  273. #if defined(GETTIMEOFDAY)
  274. sprintf(&msg_buf[22], ".%.3lu ", cur_entry->ts.tv_usec / 1000L);
  275. #else
  276. sprintf(&msg_buf[22], ".%.3hu ", cur_entry->ts.millitm);
  277. #endif
  278. buf_pos = 27;
  279. sprintf(msg_buf, "(%.4d)", cur_entry->sametime_count);
  280. msg_buf[6] = ' ';
  281. if (cur_entry->has_rc == 2)
  282. strncpy(&msg_buf[buf_pos], cur_entry->name, sizeof(msg_buf)-buf_pos);
  283. else
  284. {
  285. const char *format = Messages_get(cur_entry->number, cur_entry->level);
  286. if (cur_entry->has_rc == 1)
  287. snprintf(&msg_buf[buf_pos], sizeof(msg_buf)-buf_pos, format, cur_entry->thread_id,
  288. cur_entry->depth, "", cur_entry->depth, cur_entry->name, cur_entry->line, cur_entry->rc);
  289. else
  290. snprintf(&msg_buf[buf_pos], sizeof(msg_buf)-buf_pos, format, cur_entry->thread_id,
  291. cur_entry->depth, "", cur_entry->depth, cur_entry->name, cur_entry->line);
  292. }
  293. return msg_buf;
  294. }
  295. static void Log_output(enum LOG_LEVELS log_level, const char *msg)
  296. {
  297. if (trace_destination)
  298. {
  299. fprintf(trace_destination, "%s\n", msg);
  300. if (trace_destination != stdout && ++lines_written >= max_lines_per_file)
  301. {
  302. fclose(trace_destination);
  303. _unlink(trace_destination_backup_name); /* remove any old backup trace file */
  304. rename(trace_destination_name, trace_destination_backup_name); /* rename recently closed to backup */
  305. trace_destination = fopen(trace_destination_name, "w"); /* open new trace file */
  306. if (trace_destination == NULL)
  307. trace_destination = stdout;
  308. lines_written = 0;
  309. }
  310. else
  311. fflush(trace_destination);
  312. }
  313. if (trace_callback)
  314. (*trace_callback)(log_level, msg);
  315. }
  316. static void Log_posttrace(enum LOG_LEVELS log_level, traceEntry* cur_entry)
  317. {
  318. if (((trace_output_level == -1) ? log_level >= trace_settings.trace_level : log_level >= trace_output_level))
  319. {
  320. char* msg = NULL;
  321. if (trace_destination || trace_callback)
  322. msg = &Log_formatTraceEntry(cur_entry)[7];
  323. Log_output(log_level, msg);
  324. }
  325. }
  326. static void Log_trace(enum LOG_LEVELS log_level, const char *buf)
  327. {
  328. traceEntry *cur_entry = NULL;
  329. if (trace_queue == NULL)
  330. return;
  331. cur_entry = Log_pretrace();
  332. memcpy(&(cur_entry->ts), &ts, sizeof(ts));
  333. cur_entry->sametime_count = sametime_count;
  334. cur_entry->has_rc = 2;
  335. strncpy(cur_entry->name, buf, sizeof(cur_entry->name));
  336. cur_entry->name[MAX_FUNCTION_NAME_LENGTH] = '\0';
  337. Log_posttrace(log_level, cur_entry);
  338. }
  339. /**
  340. * Log a message. If possible, all messages should be indexed by message number, and
  341. * the use of the format string should be minimized or negated altogether. If format is
  342. * provided, the message number is only used as a message label.
  343. * @param log_level the log level of the message
  344. * @param msgno the id of the message to use if the format string is NULL
  345. * @param aFormat the printf format string to be used if the message id does not exist
  346. * @param ... the printf inserts
  347. */
  348. void Log(enum LOG_LEVELS log_level, int msgno, const char *format, ...)
  349. {
  350. if (log_level >= trace_settings.trace_level)
  351. {
  352. const char *temp = NULL;
  353. va_list args;
  354. /* we're using a static character buffer, so we need to make sure only one thread uses it at a time */
  355. Thread_lock_mutex(log_mutex);
  356. if (format == NULL && (temp = Messages_get(msgno, log_level)) != NULL)
  357. format = temp;
  358. va_start(args, format);
  359. vsnprintf(msg_buf, sizeof(msg_buf), format, args);
  360. Log_trace(log_level, msg_buf);
  361. va_end(args);
  362. Thread_unlock_mutex(log_mutex);
  363. }
  364. }
  365. /**
  366. * The reason for this function is to make trace logging as fast as possible so that the
  367. * function exit/entry history can be captured by default without unduly impacting
  368. * performance. Therefore it must do as little as possible.
  369. * @param log_level the log level of the message
  370. * @param msgno the id of the message to use if the format string is NULL
  371. * @param aFormat the printf format string to be used if the message id does not exist
  372. * @param ... the printf inserts
  373. */
  374. void Log_stackTrace(enum LOG_LEVELS log_level, int msgno, int thread_id, int current_depth, const char* name, int line, int* rc)
  375. {
  376. traceEntry *cur_entry = NULL;
  377. if (trace_queue == NULL)
  378. return;
  379. if (log_level < trace_settings.trace_level)
  380. return;
  381. Thread_lock_mutex(log_mutex);
  382. cur_entry = Log_pretrace();
  383. memcpy(&(cur_entry->ts), &ts, sizeof(ts));
  384. cur_entry->sametime_count = sametime_count;
  385. cur_entry->number = msgno;
  386. cur_entry->thread_id = thread_id;
  387. cur_entry->depth = current_depth;
  388. strcpy(cur_entry->name, name);
  389. cur_entry->level = log_level;
  390. cur_entry->line = line;
  391. if (rc == NULL)
  392. cur_entry->has_rc = 0;
  393. else
  394. {
  395. cur_entry->has_rc = 1;
  396. cur_entry->rc = *rc;
  397. }
  398. Log_posttrace(log_level, cur_entry);
  399. Thread_unlock_mutex(log_mutex);
  400. }
  401. #if 0
  402. static FILE* Log_destToFile(const char *dest)
  403. {
  404. FILE* file = NULL;
  405. if (strcmp(dest, "stdout") == 0)
  406. file = stdout;
  407. else if (strcmp(dest, "stderr") == 0)
  408. file = stderr;
  409. else
  410. {
  411. if (strstr(dest, "FFDC"))
  412. file = fopen(dest, "ab");
  413. else
  414. file = fopen(dest, "wb");
  415. }
  416. return file;
  417. }
  418. static int Log_compareEntries(const char *entry1, const char *entry2)
  419. {
  420. int comp = strncmp(&entry1[7], &entry2[7], 19);
  421. /* if timestamps are equal, use the sequence numbers */
  422. if (comp == 0)
  423. comp = strncmp(&entry1[1], &entry2[1], 4);
  424. return comp;
  425. }
  426. /**
  427. * Write the contents of the stored trace to a stream
  428. * @param dest string which contains a file name or the special strings stdout or stderr
  429. */
  430. int Log_dumpTrace(char* dest)
  431. {
  432. FILE* file = NULL;
  433. ListElement* cur_trace_entry = NULL;
  434. const int msgstart = 7;
  435. int rc = -1;
  436. int trace_queue_index = 0;
  437. if ((file = Log_destToFile(dest)) == NULL)
  438. {
  439. Log(LOG_ERROR, 9, NULL, "trace", dest, "trace entries");
  440. goto exit;
  441. }
  442. fprintf(file, "=========== Start of trace dump ==========\n");
  443. /* Interleave the log and trace entries together appropriately */
  444. ListNextElement(trace_buffer, &cur_trace_entry);
  445. trace_queue_index = start_index;
  446. if (trace_queue_index == -1)
  447. trace_queue_index = next_index;
  448. else
  449. {
  450. Log_formatTraceEntry(&trace_queue[trace_queue_index++]);
  451. if (trace_queue_index == trace_settings.max_trace_entries)
  452. trace_queue_index = 0;
  453. }
  454. while (cur_trace_entry || trace_queue_index != next_index)
  455. {
  456. if (cur_trace_entry && trace_queue_index != -1)
  457. { /* compare these timestamps */
  458. if (Log_compareEntries((char*)cur_trace_entry->content, msg_buf) > 0)
  459. cur_trace_entry = NULL;
  460. }
  461. if (cur_trace_entry)
  462. {
  463. fprintf(file, "%s\n", &((char*)(cur_trace_entry->content))[msgstart]);
  464. ListNextElement(trace_buffer, &cur_trace_entry);
  465. }
  466. else
  467. {
  468. fprintf(file, "%s\n", &msg_buf[7]);
  469. if (trace_queue_index != next_index)
  470. {
  471. Log_formatTraceEntry(&trace_queue[trace_queue_index++]);
  472. if (trace_queue_index == trace_settings.max_trace_entries)
  473. trace_queue_index = 0;
  474. }
  475. }
  476. }
  477. fprintf(file, "========== End of trace dump ==========\n\n");
  478. if (file != stdout && file != stderr && file != NULL)
  479. fclose(file);
  480. rc = 0;
  481. exit:
  482. return rc;
  483. }
  484. #endif