3
$\begingroup$

After reading:

How to count the actual occurence of a warning message in a Do loop?

I wonder about a broader question: how to count the number of occurences of a warning messages in the current session ?

My first try was

counter[arg_] := Module[{}, count++; Return[arg]];
$MessagePrePrint = counter[#] &;
count = 0;

count
Do[1/0, {k, 1, 3}];
count

Obviously,

count
Quiet[Do[1/0, {k, 1, 3}]];
count

doesn't increment the counter.

Now, to keep a tally of all message and hide them, I experimented

counterQuiet[arg_] := Module[{}, count++; Return[Null]];
$MessagePrePrint = counterQuiet[#] &;
count = 0;

count
Do[1/0, {k, 1, 3}];
count

but it isn't a smart trick, because this way messages are still visible, albeit containing Null instead of the original argument.

Can the goal be achieved without redirecting stderr to a dummy stream ?

Otherwise, how to implement the redirection and still count messages?

$\endgroup$
2
$\begingroup$

The down values of the built-in symbol MessageList track all the messages emitted in a given kernel session. It can be used to get the count you want by evaluating

 count := Total[Length /@ DownValues[MessageList][[All, 2]]];

Then each time you evaluate count, you will the current total of the messages emitted so far in your kernel session. Here is an image of an example session (starting with a fresh kernel).

session

$\endgroup$
  • $\begingroup$ Thanks for your reply ! This solution was completely beyond my capability, owing to my lack of deep understanding of MessageList. It rises to me more doubts about MessageList, and I will post them as detached questions. P.S. Please, feel always free to remark upon my error in English. I will edit my questions to adjust them. $\endgroup$ – mitochondrial Oct 6 '15 at 7:36
5
$\begingroup$
sessionCount = 0;

Check[1/0, sessionCount++; $Failed] & /@ Range[3] // Quiet;

sessionCount

(*  3  *)

Check[1/0, sessionCount++; $Failed] & /@ Range[5] // Quiet;

sessionCount

(*  8  *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.