diff --git a/mongoose.c b/mongoose.c
index 4ec535b92c043ea1085f9c6181de4c27b8054a02..a94ed7faee0d1d27f5f2d4b2ec37e886c01d2c29 100644
--- a/mongoose.c
+++ b/mongoose.c
@@ -317,10 +317,19 @@ int cs_base64_decode(const unsigned char *s, int len, char *dst) {
 #line 1 "src/../../common/cs_dbg.c"
 /**/
 #endif
+/* Amalgamated: #include "cs_dbg.h" */
+
 #include <stdarg.h>
 #include <stdio.h>
 
-void cs_dbg_printf(const char *fmt, ...) {
+enum cs_log_level s_cs_log_level =
+#ifdef CS_ENABLE_DEBUG
+    LL_DEBUG;
+#else
+    LL_ERROR;
+#endif
+
+void cs_log_printf(const char *fmt, ...) {
   va_list ap;
   va_start(ap, fmt);
   vfprintf(stderr, fmt, ap);
@@ -328,6 +337,10 @@ void cs_dbg_printf(const char *fmt, ...) {
   fputc('\n', stderr);
   fflush(stderr);
 }
+
+void cs_log_set_level(enum cs_log_level level) {
+  s_cs_log_level = level;
+}
 #ifdef NS_MODULE_LINES
 #line 1 "src/../../common/dirent.c"
 /**/
diff --git a/mongoose.h b/mongoose.h
index 74c836feb6cdc6fbf0abfe38dfbcbabd40e70b74..c9e2ce5b2392fd87e702e90a3a99596c6ea15ff4 100644
--- a/mongoose.h
+++ b/mongoose.h
@@ -106,6 +106,7 @@
 #include <assert.h>
 #include <ctype.h>
 #include <errno.h>
+#include <limits.h>
 #include <stdarg.h>
 #include <stddef.h>
 #include <stdio.h>
@@ -272,18 +273,41 @@ int64_t strtoll(const char *str, char **endptr, int base);
 #ifndef _CS_DBG_H_
 #define _CS_DBG_H_
 
-#ifdef CS_ENABLE_DEBUG
+enum cs_log_level {
+  LL_NONE = -1,
+  LL_ERROR = 0,
+  LL_WARN = 1,
+  LL_INFO = 2,
+  LL_DEBUG = 3,
 
-void cs_dbg_printf(const char *fmt, ...);
-#define __DBG(x)                         \
-  do {                                   \
+  _LL_MIN = -2,
+  _LL_MAX = 4,
+};
+
+#ifndef CS_NDEBUG
+
+extern enum cs_log_level s_cs_log_level;
+void cs_log_set_level(enum cs_log_level level);
+
+void cs_log_printf(const char *fmt, ...);
+
+#define LOG(l, x)                        \
+  if (s_cs_log_level >= l) {             \
     fprintf(stderr, "%-20s ", __func__); \
-    cs_dbg_printf x;                     \
-  } while (0)
-#define DBG __DBG
+    cs_log_printf x;                     \
+  }
 
-#else
+#define DBG(x)                           \
+  if (s_cs_log_level >= LL_DEBUG) {      \
+    fprintf(stderr, "%-20s ", __func__); \
+    cs_log_printf x;                     \
+  }
+
+#else /* NDEBUG */
+
+#define cs_log_set_level(l)
 
+#define LOG(l, x)
 #define DBG(x)
 
 #endif
@@ -1327,8 +1351,12 @@ extern "C" {
 #endif
 
 #ifndef MG_MAX_PATH
+#ifdef PATH_MAX
+#define MG_MAX_PATH PATH_MAX
+#else
 #define MG_MAX_PATH 1024
 #endif
+#endif
 
 #ifndef MG_MAX_HTTP_SEND_IOBUF
 #define MG_MAX_HTTP_SEND_IOBUF 4096