{"id":294,"date":"2011-11-04T13:59:08","date_gmt":"2011-11-04T13:59:08","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2011\/11\/04\/managing-deployed-application-output-with-message-handlers\/"},"modified":"2016-08-19T14:44:49","modified_gmt":"2016-08-19T19:44:49","slug":"managing-deployed-application-output-with-message-handlers","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2011\/11\/04\/managing-deployed-application-output-with-message-handlers\/","title":{"rendered":"Managing Deployed Application Output with Message Handlers"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>Guest blogger <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/4660\">Peter Webb<\/a> returns with another in an <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/deployment\/\">occasional series<\/a> of postings about application deployment.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Two Output Streams<\/a><\/li>\r\n         <li><a href=\"#2\">A Function with Output<\/a><\/li>\r\n         <li><a href=\"#3\">Where are the Handlers?<\/a><\/li>\r\n         <li><a href=\"#4\">Logging Messages to a File<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Two Output Streams<a name=\"1\"><\/a><\/h3>\r\n   <p>Programs running in interactive <a href=\"https:\/\/www.mathworks.com\/products\/matlab\">MATLAB<\/a> send <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/error.html\">error<\/a>, <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/warning.html\">warning<\/a> and <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/disp.html\">informational<\/a> text messages to the MATLAB command window. By default, deployed applications output text to the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Standard_streams\"><i>standard output<\/i> and <i>standard error<\/i><\/a> streams.\r\n   <\/p>\r\n   <p>In many cases, particularly for <a href=\"http:\/\/en.wikipedia.org\/wiki\/Console_application\">console applications<\/a> on Windows and UNIX, this works well enough: the output appears in the DOS window or UNIX terminal. However, non-console\r\n      applications (and any type of <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/f2-995712.html\">shared library<\/a> or <a href=\"https:\/\/www.mathworks.com\/products\/netbuilder\/\">builder component<\/a>) may be unable to access either of the standard output streams; messages sent to those streams will be lost. To avoid losing\r\n      messages when the standard streams are unavailable, deployed applications register output and error <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/f2-998954.html#f2-1008529\"><i>message handlers<\/i><\/a>. A message handler directs formatted text messages to a persistent or visible location, typically a log file or an output\r\n      window.\r\n   <\/p>\r\n   <p>In this post, I'll show you how to send both error and informational messages to a log file.<\/p>\r\n   <h3>A Function with Output<a name=\"2\"><\/a><\/h3>\r\n   <p>To demonstrate output redirection, I wrote the <tt>sendmessages<\/tt> function, which displays an informational message and a warning, and then issues an error:\r\n   <\/p><pre>function sendmessages(info, warn, err)\r\n    disp(info);\r\n    warning(warn);\r\n    error(err);<\/pre><p>In order to follow the rest of this posting, you'll need the <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/30567-managing-deployed-application-output-with-message-handlers\">source code<\/a> from MATLAB Central, particularly the C main program, <tt>log.c<\/tt>. See <tt>logREADME<\/tt> in the ZIP file for a complete description of distributed files and step-by-step directions for building the application.\r\n   <\/p>\r\n   <h3>Where are the Handlers?<a name=\"3\"><\/a><\/h3>\r\n   <p>Create a C shared library from the example function with <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/f0-985134.html\">MATLAB Compiler<\/a>:\r\n   <\/p><pre>mcc -Ngv -W lib:libmsgfcn -T link:lib sendmessages.m<\/pre><p>Open the generated wrapper file, <tt>libmsgfcn.c<\/tt>, in a text editor. The wrapper file contains two default handlers, <tt>mclDefaultErrorHandler<\/tt> and <tt>mclDefaultPrintHandler<\/tt>. The generated code contains two library initialization functions: <tt>libmsgfcnInitialize<\/tt> and <tt>libmsgfcnInitializeWithHandlers<\/tt>. You redirect program output by passing your custom message handlers to <tt>libmsgfcnInitializeWithHandlers<\/tt>. All message handlers conform to the same interface:\r\n   <\/p><pre> static int MessageHandler(const char *message)<\/pre><p>You never need to call the message handler directly. The <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/f12-999353.html\">MATLAB Compiler Runtime<\/a> (MCR) calls your message handler automatically.\r\n   <\/p>\r\n   <h3>Logging Messages to a File<a name=\"4\"><\/a><\/h3>\r\n   <p>A common use for a message handler is to record messages and the time they occurred in a log file. This type of message handler\r\n      requires only a few lines of C code:\r\n   <\/p><pre>static FILE *logFile = NULL;<\/pre><pre>static int LogFileHandler(const char *s)\r\n{\r\n    if (logFile != NULL)\r\n    {\r\n        time_t now = time(NULL);\r\n        fprintf(logFile, \"%s\", ctime(&amp;now));\r\n        fprintf(logFile, \"%s\\n\", s);\r\n    }\r\n}<\/pre><p>Your main program needs to open and close the log file, of course. Open the log file before calling the library initialization\r\n      function and close it after calling <tt>mclTerminateApplication<\/tt>. See the full implementation in <tt>log.c<\/tt>.\r\n   <\/p>\r\n   <p>Build the application with <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/mbuild.html\">mbuild<\/a>:\r\n   <\/p>\r\n   <p>(UNIX):    <tt>mbuild -g log.c -L. -lmsgfcn<\/tt><\/p>\r\n   <p>(Windows): <tt>mbuild -g log.c libmsgfcn.lib<\/tt><\/p>\r\n   <p>Run it from a DOS shell or UNIX terminal window:<\/p>\r\n   <p>(UNIX):    <tt>.\/log \"information\" \"look out!\" \"oops.\"<\/tt><\/p>\r\n   <p>(Windows): <tt>log \"information\" \"look out!\" \"oops.\"<\/tt><\/p>\r\n   <p>The example program creates the log file <tt>MessageLog.txt<\/tt> to capture program output.\r\n   <\/p><pre>Fri Aug 19 11:53:32 2011\r\ninformation<\/pre><pre>Fri Aug 19 11:53:32 2011\r\nWarning: lookout!\r\n&gt; In sendmessages at 3<\/pre><pre>Fri Aug 19 11:53:32 2011\r\nError using sendmessages (line 4)\r\noops.<\/pre><p>Next time, I'll show you how to display log messages in a persistent window, and how to distinguish between errors and informational\r\n      messages. In the meantime, <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=294#respond\">let me know<\/a> how your applications manage output. Does your code need to distinguish between program output and error messages?\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_f3ccb97df46c4a819de5bfa553b5d8ac() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='f3ccb97df46c4a819de5bfa553b5d8ac ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' f3ccb97df46c4a819de5bfa553b5d8ac';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Peter Webb';\r\n        copyright = 'Copyright 2011 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \r\n-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_f3ccb97df46c4a819de5bfa553b5d8ac()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.13<br><\/p>\r\n<\/div>\r\n<!--\r\nf3ccb97df46c4a819de5bfa553b5d8ac ##### SOURCE BEGIN #####\r\n%% Managing Deployed Application Output with Message Handlers\r\n% Guest blogger \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/4660 Peter Webb>\r\n% returns with another in an \r\n% <https:\/\/blogs.mathworks.com\/loren\/category\/deployment\/ occasional series>\r\n% of postings about application deployment. \r\n\r\n%% Two Output Streams\r\n% Programs running in interactive \r\n% <https:\/\/www.mathworks.com\/products\/matlab MATLAB>\r\n% send \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/error.html error>,\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/warning.html warning> and\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/disp.html informational>\r\n% text messages to the MATLAB command window. By default, deployed \r\n% applications output text to the \r\n% <http:\/\/en.wikipedia.org\/wiki\/Standard_streams _standard output_ and \r\n% _standard error_> streams. \r\n% \r\n% In many cases, particularly for \r\n% <http:\/\/en.wikipedia.org\/wiki\/Console_application console applications>\r\n% on Windows\r\n% and UNIX, this works well enough: the output appears in the DOS window or\r\n% UNIX terminal. However, non-console applications (and any type of \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/f2-995712.html \r\n% shared library> or \r\n% <https:\/\/www.mathworks.com\/products\/netbuilder\/ builder component>) \r\n% may be unable to access either of the \r\n% standard output streams; messages sent to those streams will be lost. To\r\n% avoid losing messages when the standard streams are unavailable, \r\n% deployed applications register output and error \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/f2-998954.html#f2-1008529\r\n% _message handlers_>. \r\n% A message handler directs formatted text messages to a persistent or\r\n% visible location, typically a log file or an output window.\r\n%\r\n% In this post, I'll show you how to send both error and informational\r\n% messages to a log file.\r\n%\r\n%% A Function with Output\r\n% To demonstrate output redirection, I wrote the |sendmessages| function,\r\n% which displays an informational message and a warning, and then issues an\r\n% error:\r\n%\r\n%  function sendmessages(info, warn, err)\r\n%      disp(info);\r\n%      warning(warn);\r\n%      error(err); \r\n%\r\n% In order to follow the rest of this posting, you'll need the \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/30567-managing-deployed-application-output-with-message-handlers \r\n% source code>\r\n% from MATLAB Central, particularly the C main program, |log.c|. See\r\n% |logREADME| in the ZIP file for a complete description of distributed\r\n% files and step-by-step directions for building the application.\r\n%\r\n%% Where are the Handlers?\r\n% Create a C shared library from the example function with \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/f0-985134.html\r\n% MATLAB Compiler>:\r\n%\r\n%  mcc -Ngv -W lib:libmsgfcn -T link:lib sendmessages.m\r\n%\r\n% Open the generated wrapper file, |libmsgfcn.c|, in a text editor. The\r\n% wrapper file contains two default handlers, |mclDefaultErrorHandler| and\r\n% |mclDefaultPrintHandler|. The generated code contains two library initialization \r\n% functions: |libmsgfcnInitialize| and |libmsgfcnInitializeWithHandlers|.\r\n% You redirect program output by passing your custom message handlers to\r\n% |libmsgfcnInitializeWithHandlers|. All message handlers conform to the\r\n% same interface:\r\n%\r\n%   static int MessageHandler(const char *message)\r\n%\r\n% You never need to call the message handler directly. The \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/f12-999353.html \r\n% MATLAB Compiler Runtime> (MCR) calls your message handler automatically.\r\n% \r\n%% Logging Messages to a File\r\n% A common use for a message handler is to record messages and the time\r\n% they occurred in a log file. This type of message handler requires only a\r\n% few lines of C code:\r\n%\r\n%  static FILE *logFile = NULL;\r\n%\r\n%  static int LogFileHandler(const char *s)\r\n%  {\r\n%      if (logFile != NULL)\r\n%      {\r\n%          time_t now = time(NULL);\r\n%          fprintf(logFile, \"%s\", ctime(&now));\r\n%          fprintf(logFile, \"%s\\n\", s);\r\n%      }\r\n%  }\r\n%\r\n% Your main program needs to open and close the log file, of course. Open\r\n% the log file before calling the library initialization function and close\r\n% it after calling |mclTerminateApplication|. See the full implementation\r\n% in |log.c|.\r\n%\r\n% Build the application with \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/compiler\/mbuild.html \r\n% mbuild>:\r\n%\r\n% (UNIX):    |mbuild -g log.c -L. -lmsgfcn|\r\n%\r\n% (Windows): |mbuild -g log.c libmsgfcn.lib|\r\n%\r\n% Run it from a DOS shell or UNIX terminal window:\r\n%\r\n% (UNIX):    |.\/log \"information\" \"look out!\" \"oops.\"|\r\n%\r\n% (Windows): |log \"information\" \"look out!\" \"oops.\"|\r\n%\r\n% The example program creates the log file |MessageLog.txt| to capture\r\n% program output.\r\n%\r\n%  Fri Aug 19 11:53:32 2011\r\n%  information\r\n%\r\n%  Fri Aug 19 11:53:32 2011\r\n%  Warning: lookout!\r\n%  > In sendmessages at 3\r\n%  \r\n%  Fri Aug 19 11:53:32 2011\r\n%  Error using sendmessages (line 4)\r\n%  oops. \r\n% \r\n% Next time, I'll show you how to display log messages in a persistent\r\n% window, and how to distinguish between errors and informational messages.\r\n% In the meantime, <http:\/\/blogs\/mathworks.com\/loren\/?p=294#respond \r\n% let me know> how your applications manage output. Does\r\n% your code need to distinguish between program output and error messages?\r\n##### SOURCE END ##### f3ccb97df46c4a819de5bfa553b5d8ac\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Guest blogger Peter Webb returns with another in an occasional series of postings about application deployment.\r\n      \r\n   \r\n   Contents\r\n   \r\n      \r\n   ... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2011\/11\/04\/managing-deployed-application-output-with-message-handlers\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/294"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=294"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/294\/revisions"}],"predecessor-version":[{"id":2011,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/294\/revisions\/2011"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=294"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=294"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=294"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}