I am testing using CloudDeploy[APIFunction[...]]
. I can not find any info about real time logging.
If there is any problem happening with the cloud deployed API, how can I debug it?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityI am testing using CloudDeploy[APIFunction[...]]
. I can not find any info about real time logging.
If there is any problem happening with the cloud deployed API, how can I debug it?
I will show you a small piece of code you can use as a starting point, it is already nice enough.
Just compose withLogger[apiPath]
with your APIFunction's function. And initialize the log file.
Like this:
With[{apiPath = "api/foo"},
CloudPut["#API init " <> DateString[], apiPath <> ".log"];
CloudDeploy[
APIFunction[
{"x" -> "Integer"}
, withLogger[apiPath] @ Check[ (*!*)
Print["start"]
; 1 / Echo[#x]
, GenerateHTTPResponse[Echo @ HTTPErrorResponse[500]]
] &
]
, apiPath
, Permissions -> "Public"
]
]
(*! - only that line matters, everything else is only to show the point*)
withLogger
is defined at the end of the post. Here is an example:
withLogger[parentPath_] := Function[expr,
Module[{logFile, log, res, timeMark},
timeMark = AbsoluteTime[];
logFile = parentPath <> ".log";
Quiet@OpenAppend[logFile, FormatType -> (OutputForm),
PageWidth -> Infinity];
log[type : "INFO" | "DEBUG" | "MESSAGE" : "INFO", msg__] := Write[
logFile,
DateString[{"ISODate", " ", "Time", ".", "Millisecond", " "}],
$SessionID, " ",
$RequesterWolframID, " ",
type, " ",
Sequence @@ Riffle[{msg}, " "]
];
Block[{Print, Echo, messageString},
Print = log;
Echo[input_, label_: "", pipe_: Identity] := CompoundExpression[
Print["INFO", label /. "" :> (## &[]), pipe@input],
input
];
messageString[
Hold[Message[msg : MessageName[head_, name_], args___], _]] :=
ToString[StringForm[msg /. Messages[head], args]];
Internal`HandlerBlock[
{"Message", If[Last[#], Print["MESSAGE", messageString[#]]] &},
Print["--------------- API CALL EXECUTION --------------"];
res = expr;
Print@
StringTemplate["Kernel evaluation time `` [s]"][
AbsoluteTime[] - timeMark];
res
]
]
]
, HoldAllComplete
]