diff --git a/main/astobj2.c b/main/astobj2.c
index 63058e19e34c5ca12968bab36caa254fe1503193..91ebc1e2c9314c9926a0e6639179aa18836e2f85 100644
--- a/main/astobj2.c
+++ b/main/astobj2.c
@@ -1193,8 +1193,11 @@ int astobj2_init(void)
 		}
 	}
 
+	ast_register_cleanup(astobj2_cleanup);
+
 	if (container_init() != 0) {
 		fclose(ref_log);
+		ref_log = NULL;
 		return -1;
 	}
 
@@ -1202,7 +1205,5 @@ int astobj2_init(void)
 	ast_cli_register_multiple(cli_astobj2, ARRAY_LEN(cli_astobj2));
 #endif	/* defined(AO2_DEBUG) */
 
-	ast_register_cleanup(astobj2_cleanup);
-
 	return 0;
 }