StreamLogging.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 |
<# .SYNOPSIS PowerShell module implementing logging to the console and/or text files using StreamWriter. .LINK https://github.com/alekdavis/StreamLogging #> #------------------------------[ IMPORTANT ]------------------------------- <# PLEASE MAKE SURE THAT THE SCRIPT STARTS WITH THE COMMENT HEADER ABOVE AND THE HEADER IS FOLLOWED BY AT LEAST ONE BLANK LINE; OTHERWISE, GET-HELP AND GETVERSION COMMANDS WILL NOT WORK. #> #------------------------[ RUN-TIME REQUIREMENTS ]------------------------- #Requires -Version 4.0 #---------------------------[ MODULE VARIABLES ]--------------------------- # Log targets. $TARGET_CONSOLE = "Console" $TARGET_FILE = "File" # Log levels. $LOGLEVEL_NONE = "None" $LOGLEVEL_ERROR = "Error" $LOGLEVEL_WARNING = "Warning" $LOGLEVEL_INFO = "Info" $LOGLEVEL_DEBUG = "Debug" # Numeric values of log levels (lower number takes precedence). $LogLevels = @{ $LOGLEVEL_NONE = 0; $LOGLEVEL_ERROR = 1; $LOGLEVEL_WARNING = 2; $LOGLEVEL_INFO = 3; $LOGLEVEL_DEBUG = 4 } # Loge level prefixes for log and error files. $LogPrefixes = @{ $LOGLEVEL_ERROR = "ERROR"; $LOGLEVEL_WARNING = "WARN "; $LOGLEVEL_INFO = "INFO "; $LOGLEVEL_DEBUG = "DEBUG" } # Log configuration settings. $Config = [PSCustomObject]@{ Initialized = $false LogLevel = $null Console = $false File = $false ErrorFile = $false FilePath = $null ErrorFilePath = $null Backup = $false Overwrite = $false Append = $false WithLogLevel = $false WithTimestamp = $false TimestampFormat = $null UtcTime = $null TabSize = 2 BackgroundColor = $null ForegroundColor = $null } # Log stream writers. $Stream = [PSCustomObject]@{ LogFile = $null ErrorFile = $null } # Console font and background colors. # It would be nice to get colors dynamically, but this would break in # PowerShell ISE because it uses 32-bit colors instead of 8-bit colors. $COLOR_ERROR = "Red" $COLOR_WARNING = "Yellow" $COLOR_DEBUG = "Gray" $BACKGROUND_COLOR = "Black" $ForegroundColors = @{ $LOGLEVEL_ERROR = $COLOR_ERROR # $Host.PrivateData.ErrorForegroundColor $LOGLEVEL_WARNING = $COLOR_WARNING # $Host.PrivateData.WarningForegroundColor $LOGLEVEL_INFO = $null $LOGLEVEL_DEBUG = $COLOR_DEBUG # $Host.PrivateData.DebugForegroundColor } $BackgroundColors = @{ $LOGLEVEL_ERROR = $BACKGROUND_COLOR # $Host.PrivateData.ErrorBackgroundColor $LOGLEVEL_WARNING = $BACKGROUND_COLOR # $Host.PrivateData.WarningBackgroundColor $LOGLEVEL_INFO = $null $LOGLEVEL_DEBUG = $BACKGROUND_COLOR # $Host.PrivateData.DebugBackgroundColor } # File extensions. $LOGFILE_EXT_DEFAULT = ".log" $ERRFILE_EXT_DEFAULT = ".err.log" $BACKUP_EXT_DEFAULT = ".txt" $CONFIGFILE_EXT_DEFAULT = ".json" $CONFIGFILE_NAMEEXT_DEFAULT = ".StreamLogging" + $CONFIGFILE_EXT_DEFAULT #---------------------------[ PRIVATE FUNCTIONS ]-------------------------- #-------------------------------------------------------------------------- # FormatLine # Formats line before it is written to the console or a file. function FormatLine { [CmdletBinding()] param ( [string] $line, [int] $indent, [string] [ValidateSet("Error", "Warning", "Info", "Debug")] $logLevel, [string] [ValidateSet("Console", "File")] $logType ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } $indentPrefix = ""; $timePrefix = ""; $logLevelPrefix = ""; $prefix = ""; # Set indent prefix. if ($indent -gt 0) { $space = " " $tab = "" for ($i=0; $i -lt $Script:Config.TabSize; $i++) { $tab += $space } for ($i=0; $i -lt $indent; $i++) { $indentPrefix += $tab } } # When logging to file, set optional timestamp and log level prefixes. if ($logType -eq "File") { if ($Script:Config.WithTimestamp) { if ($Script:Config.UtcTime) { $timePrefix = ((Get-Date). ToUniversalTime()). ToString($Script:Config.TimestampFormat) } else { $timePrefix = (Get-Date).ToString($Script:Config.TimestampFormat) } } if ($Script:Config.WithLogLevel) { $logLevelPrefix = $Script:LogPrefixes[$logLevel] } } # Add separators between prefixes. if ($timePrefix) { $prefix = $timePrefix + ":" } if ($logLevelPrefix) { $prefix += ($logLevelPrefix + ":") } if ($prefix) { $prefix += (" " + $indentPrefix) } else { if ($indentPrefix) { $prefix = $indentPrefix } } return $prefix + $line } #-------------------------------------------------------------------------- # FormatError # Returns error message from exception and inner exceptions. function FormatError { [CmdletBinding()] param ( $ex ) if (!$ex) { return $null } [string]$message = $null while ($ex) { if ($message) { $message += " " } $message = $ex.Message.Trim() $ex = $ex.InnerException } return $message } #-------------------------------------------------------------------------- # ImportConfigFile # Sets local variables of a caller to the values from a config file. # This function was adopted from: # https://www.powershellgallery.com/packages/ConfigFile function ImportConfigFile { [CmdletBinding()] param ( [string] $ConfigFile, [Hashtable] $DefaultParameters = $null ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (-not $PSBoundParameters.ContainsKey('Verbose'))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (-not $PSBoundParameters.ContainsKey('Debug'))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } # If config file was explicitly specified, make sure it exists. if ($ConfigFile) { if (!(Test-Path -Path $ConfigFile -PathType Leaf)) { # Given file does not exist. Try appending it to invoking script. $configFilePath = $null if ($PSCmdlet) { $configFilePath = $Script:MyInvocation.PSCommandPath + $ConfigFile } else { $configFilePath = $Script:PSCommandPath + $ConfigFile } if (!(Test-Path -Path $configFile -PathType Leaf)) { throw "Config file '" + $ConfigFile + "' is not found." } $ConfigFile = $configFilePath } } # If path is not specified, use the default (script + .json extension). else { # Default config file is named after running script with .json extension. if ($PSCmdlet) { # If this is in a module, get the module name and append it to script with # '.json' extension. $ext = "." + [io.path]::GetFileNameWithoutExtension($PSCommandPath) $ConfigFile = $Script:MyInvocation.PSCommandPath + $ext + $CONFIGFILE_EXT_DEFAULT } else { # If this is in a script, name must be hard coded. $ConfigFile = $Script:PSCommandPath + $CONFIGFILE_NAMEEXT_DEFAULT } # Default config file is optional. if (!(Test-Path -Path $ConfigFile -PathType Leaf)) { Write-Verbose "Config file '$ConfigFile' is not found." return } } $count = 0 Write-Verbose "Loading config file '$ConfigFile'." # Process file. $jsonString = Get-Content $ConfigFile -Raw ` -ErrorAction:SilentlyContinue -WarningAction:SilentlyContinue if (!$jsonString) { Write-Verbose "Config file is empty." return } Write-Verbose "Converting config file settings into a JSON object." $jsonObject = $jsonString | ConvertFrom-Json ` -ErrorAction:SilentlyContinue -WarningAction:SilentlyContinue if (!$jsonObject) { Write-Verbose "Cannot convert config file settings into a JSON object." return } $strict = ($jsonObject._meta.strict -or $jsonObject.meta.strict) $prefix = $jsonObject._meta.prefix if (!$prefix) { $jsonObject.meta.prefix } if (!$prefix) { $prefix = "_" } # Process elements twice: first, literals, then the ones that require expansion. # Technically, when using the module, one pass would suffice, since the only # supported expandable values are environment variables (%%) or PowerShell # environment variables ($env:) and these can be resolved in a single pass. # But in case this function is copied into and used directly from a script # (not from a module), the second pass is needed in case a value references # a script variable. Again, keep in mind that script variable expansion is not # supported when using the module. for ($i=0; $i -lt 2; $i++) { $jsonObject.PSObject.Properties | ForEach-Object { # Copy properties to variables for readability. $hasValue = $_.Value.hasValue $name = $_.Name $value = $null $value = $_.Value.value # In ForEach-Object loops 'return' acts as 'continue' in loops. if ($name.StartsWith($prefix)) { # Skip to next (yes, 'return' is the right statement here). return } # If 'hasValue' is explicitly set to 'false', ignore element. if ($hasValue -eq $false) { return } # Now, the 'hasValue' is either missing or is set to 'true'. # In the strict mode, 'hasValue' must be set to include the element. if ($strict -and ($null -eq $hasValue)) { return } # If 'hasValue' is not set and the value resolves to 'false', ignore it. if (($null -eq $hasValue) -and (!$value)) { return } # Check if parameter is specified on command line. if ($DefaultParameters) { if ($DefaultParameters.ContainsKey($name)) { return } } # Okay, we must use the value. # The value must be expanded if it: # - is not marked as a literal, # - has either '%' or '$' character (not the $ end-of-line special character), # - is neither of PowerShell constants that has a '$' character in name # ($true, $false, $null). if ((!$_.Value.literal) -and (($value -match "%") -or ($value -match "\$")) -and ($value -ne $true) -and ($value -ne $false) -and ($null -ne $value)) { # Skip on the first iteration in case it depends on the unread variable. if ($i -eq 0) { $name = $null } # Process on second iteration. else { if ($value -match "%") { # Expand environment variable. $value = [System.Environment]::ExpandEnvironmentVariables($value) } else { # Expand PowerShell variable. $value = $ExecutionContext.InvokeCommand.ExpandString($value) } } } else { # Non-expandable variables have already been processed in the first iteration. if ($i -eq 1) { $name = $null } } if ($name) { if ($count -eq 0) { Write-Verbose "Setting variable(s):" } Write-Verbose "-$name '$value'" # Scope 1 is the scope of the function in the module that called this function. Set-Variable -Scope 1 -Name $name -Value $value -Force -Visibility Public $count++ } } } if ($count -gt 0) { Write-Verbose "Done setting $count variable(s) from the config file." } } #-------------------------------------------------------------------------- # Initialize # Initializes log settings function Initialize { [CmdletBinding()] param ( ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } if ($Script:Config.Initialized) { Write-Verbose "Resetting stream logging properties." } else { Write-Verbose "Setting stream logging properties." } $Script:Config.Initialized = $false $Script:Config.LogLevel = $null $Script:Config.Console = $false $Script:Config.File = $false $Script:Config.ErrorFile = $false $Script:Config.FilePath = $null $Script:Config.ErrorFilePath = $null $Script:Config.Backup = $false $Script:Config.Overwrite = $false $Script:Config.Append = $false $Script:Config.WithLogLevel = $false $Script:Config.WithTimestamp = $false $Script:Config.TimestampFormat = $null $Script:Config.UtcTime = $null $Script:Config.TabSize = 2 $Script:Config.BackgroundColor = $null $Script:Config.ForegroundColor = $null $Script:ForegroundColors = @{ $LOGLEVEL_ERROR = $COLOR_ERROR $LOGLEVEL_WARNING = $COLOR_WARNING $LOGLEVEL_INFO = $null $LOGLEVEL_DEBUG = $COLOR_DEBUG } $Script:BackgroundColors = @{ $LOGLEVEL_ERROR = $BACKGROUND_COLOR $LOGLEVEL_WARNING = $BACKGROUND_COLOR $LOGLEVEL_INFO = $null $LOGLEVEL_DEBUG = $BACKGROUND_COLOR } if ($Script:Stream.LogFile) { Write-Verbose "Closing log file stream." try { $Script:Stream.LogFile.Dispose() } catch { Write-Verbose "Error closing log file stream:" Write-Verbose $_.Exception.Message } $Script:Stream.LogFile = $null } if ($Script:Stream.ErrorFile) { Write-Verbose "Closing error file stream." try { $Script:Stream.ErrorFile.Dispose() } catch { Write-Verbose "Error closing error file stream:" Write-Verbose $_.Exception.Message } $Script:Stream.ErrorFile = $null } } #-------------------------------------------------------------------------- # IsLoggableMessage # Checks if there is a valid message. function IsLoggableMessage { [CmdletBinding()] param ( [string] $message, [int] $indent ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } if (($message -eq $null) -and ($indent -eq 0)) { return $false } return $true } #-------------------------------------------------------------------------- # IsLoggableToConsole # Checks if the message should be logged to the console. function IsLoggableToConsole { [CmdletBinding()] param ( [string] [ValidateSet("Error", "Warning", "Info", "Debug")] $logLevel ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } if ($Script:Config.LogLevel -eq $LOGLEVEL_NONE) { return $false } if (!($Script:Config.Console)) { return $false } if ($Script:LogLevels[$logLevel] -gt $Script:LogLevels[$Script:Config.LogLevel]) { return $false } return $true } #-------------------------------------------------------------------------- # IsLoggableToFile # Checks if the message should be logged to a log or error file. function IsLoggableToFile { [CmdletBinding()] param ( [string] [ValidateSet("Error", "Warning", "Info", "Debug")] $logLevel, [bool] $errFile = $false ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } if ($Script:Config.LogLevel -eq $LOGLEVEL_NONE) { return $false } if ($Script:LogLevels[$logLevel] -gt $Script:LogLevels[$Script:Config.LogLevel]) { return $false } if ($errFile) { if ($logLevel -ne $LOGLEVEL_ERROR) { return $false } if (!($Script:Config.ErrorFile)) { return $false } return $true } if (!($Script:Config.File)) { return $false } return $true } #-------------------------------------------------------------------------- # LogToConsole # Writes log message to the console. function LogToConsole { [CmdletBinding()] param ( [string] [ValidateSet("Error", "Warning", "Info", "Debug")] $logLevel, [string] $message, [int] $indent ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } # If background color was explicitly specified, use it; # otherwise, get it from hard coded configuration. if ($Script:Config.BackgroundColor) { $bgColor = $Script:Config.BackgroundColor } else { $bgColor = $Script:BackgroundColors[$logLevel] } # If foreground color was explicitly specified, use it; # otherwise, get it from hard coded configuration. if ($Script:Config.ForegroundColor) { $fontColor = $Script:Config.ForegroundColor } else { $fontColor = $Script:ForegroundColors[$logLevel] } # Only set non-null color values. $colorParams = @{} if ($fontColor) { $colorParams.Add("ForegroundColor", $fontColor) } if ($bgColor) { $colorParams.Add("BackgroundColor", $bgColor) } # Split text into separate lines. $lines = ($message -split '\r?\n') # Print each line. foreach ($line in $lines) { # But format the line first. $line = FormatLine $line $indent $logLevel $TARGET_CONSOLE Write-Host $line @colorParams } } #-------------------------------------------------------------------------- # LogToFile # Writes log message to the log or error file. function LogToFile { [CmdletBinding()] param ( [string] [ValidateSet("Error", "Warning", "Info", "Debug")] $logLevel, [string] $message, [int] $indent, [bool] $errFile = $false ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } # If the file has not been open, yet, do it now. if ($errFile) { if (!($Script:Stream.ErrorFile)) { $Script:Stream.ErrorFile = OpenFile $Script:Config.ErrorFilePath $true } } else { if (!($Script:Stream.LogFile)) { $Script:Stream.LogFile = OpenFile $Script:Config.FilePath $false } } # Process text one line at a time. $lines = ($message -split '\r?\n') foreach ($line in $lines) { # Format line first. $line = FormatLine $line $indent $logLevel $TARGET_FILE # Write line to the appropriate file: log or error. if ($errFile) { if ($Script:Stream.ErrorFile) { $Script:Stream.ErrorFile.WriteLine($line) $Script:Stream.ErrorFile.Flush() } } else { if ($Script:Stream.LogFile) { $Script:Stream.LogFile.WriteLine($line) $Script:Stream.LogFile.Flush() } } } } #-------------------------------------------------------------------------- # OpenFile # Opens log or error file (backs up, appends or overwrites old file, if needed). function OpenFile { [CmdletBinding()] param ( [string] $filePath, [bool] $errFile = $false ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } # First, check if file already exists. if (Test-Path -Path $filePath -PathType Leaf) { Write-Verbose "File '$filePath' exists." # Append existing file. if ($Script:Config.Append) { Write-Verbose "Opening file '$filePath' for appending." return (New-Object -TypeName System.IO.StreamWriter $filePath, $true) } # Overwrite existing file. elseif ($Script:Config.Overwrite) { Write-Verbose "Overwriting file '$filePath'." return (New-Object -TypeName System.IO.StreamWriter ` $filePath, $false, ([System.Text.Encoding]::UTF8)) } # Back up existing file, and create a new one. else { $timeStamp = $null $timeFormat = "yyyyMMddHHmmss" $fileName = $null $fileDir = $null do { # If generated file already exists, sleep for a second. if ($timeStamp) { Start-Sleep -s 1 } # Generate timestamp based on local or UTC time. if ($Script:Config.UtcTime) { $timeStamp = ((Get-Date). ToUniversalTime()). ToString($timeFormat) } else { $timeStamp = (Get-Date).ToString($timeFormat) } # Build new filename with timestamp. $fileName = (Split-Path -Path $filePath -Leaf) + ".$timeStamp$BACKUP_EXT_DEFAULT" # Get path to the folder holding the file. $fileDir = Split-Path -Path $filePath -Parent # Repeat until we generate a name of a non-existent file. } while (Test-Path -Path (Join-Path $fileDir $fileName)) Write-Verbose "Renaming file '$filePath' to '$fileName'." Rename-Item -Path $filePath -NewName $fileName | Out-Null } } # At this point, the file does not exist. # Get path to the folder holding the file. $fileDir = Split-Path -Path $filePath -Parent # Make sure the folder exists. if (!(Test-Path -Path $fileDir -PathType Container)) { Write-Verbose "Creating directory '$fileDir'." New-Item -Path $fileDir -ItemType Directory -Force | Out-Null } Write-Verbose "Creating file '$filePath'." return (New-Object -TypeName System.IO.StreamWriter ` $filePath, $false, ([System.Text.Encoding]::UTF8)) } #-------------------------------------------------------------------------- # SerializeObject # Converts object to a JSON or XML string. function SerializeObject { [CmdletBinding()] param ( [Parameter(Position=0,ValueFromPipeline)] [object] $object, [Parameter(Position=1)] [bool] $xml, [Parameter(Position=2)] [bool] $compress ) if ($xml) { return ($object | ConvertTo-Xml -As String).Trim() } else { if ($compress) { return ($object | ConvertTo-Json -Compress).Trim() } else { return ($object | ConvertTo-Json).Trim() } } } #-------------------------------------------------------------------------- # WriteLog # Writes log entry to the console and/or log files. function WriteLog { [CmdletBinding()] param ( [string] [ValidateSet("Error", "Warning", "Info", "Debug")] $logLevel, [string] $message, [int] $indent, [bool] $writeToConsole, [bool] $writeToFile ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } if (!(IsLoggableMessage $message $indent)) { return } # Write message to the console. if ($writeToConsole -and (IsLoggableToConsole $logLevel)) { LogToConsole $logLevel $message $indent } # Write message to the log file. if ($writeToFile -and (IsLoggableToFile $logLevel $false)) { LogToFile $logLevel $message $indent $false } # Write message to the error file. if ($writeToFile -and (IsLoggableToFile $logLevel $true)) { LogToFile $logLevel $message $indent $true } } #---------------------------[ EXPORTED FUNCTIONS ]------------------------- <# .SYNOPSIS Formats the path of a log or error file from the specified file parts following the standard naming conventions. .DESCRIPTION Use this function to tweak parts of the default log or error file. By default, a log file is named after the calling PowerShell script with the same path and an appropriate extension. For example, when invoked from 'C:\Scripts\MyScript.ps1', the default log and error file paths will be formatted as: - C:\Scripts\MyScript.log - C:\Scripts\MyScript.err.log You can tell this function to use the same formatting algorithm but use your own custom values for path to the directory, name, or extension. Say, you want to follow the same naming convention, but have the file in a different directory, such as 'D:\Logs'. In this case, just pass the name of the custom directory, such as: $logFilePath = Format-LogFilePath -Directory "D:\Logs" $errFilePath = Format-LogFilePath -Directory "D:\Logs" -IsErrorFile The generated paths will look like: - D:\Logs\MyScript.log - D:\Logs\MyScript.err.log In a similar manner, you can customize, names of the files and/or their extensions. .PARAMETER Directory Specifies the custom directory path that will be used in the file path. .PARAMETER Name Specifies the custom file name (without extension) that will be used in the file path. .PARAMETER Extension Specifies the custom file extension that will be used in the file path. .PARAMETER IsErrorFile Indicates that the generated path will be for the error file. If not specified, the standard log file is assumed. .LINK https://github.com/alekdavis/StreamLogging .INPUTS None. .OUTPUTS None. .EXAMPLE $logFilePath = Format-LogFilePath -Directory "D:\Logs" Generates path of the log file with the custom directory path. .EXAMPLE $errFilePath = Format-LogFilePath -Directory "D:\Logs" -IsErrorFile Generates path of the error file with the custom directory path. .EXAMPLE $logFilePath = Format-LogFilePath -Name "$env:computername" Generates path of the log file with the custom name. .EXAMPLE $errFilePath = Format-LogFilePath -Name "$env:computername" -IsErrorFile Generates path of the error file with the custom name. .EXAMPLE $logFilePath = Format-LogFilePath -Extension ".txt" Generates path of the log file with the custom extension. .EXAMPLE $errFilePath = Format-LogFilePath -Extension ".error" -IsErrorFile Generates path of the error file with the custom extension. #> function Format-LogFilePath { [CmdletBinding()] param ( [Alias("Dir", "Folder")] [string] $Directory, [string] $Name, [Alias("Ext")] [string] $Extension, [Alias("IsError", "ErrorFile", "Err")] [switch] $IsErrorFile ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } $path = $null if ($PSCmdlet) { $path = $MyInvocation.PSCommandPath } else { $path = $PSCommandPath } if (!($Directory)) { $Directory = Split-Path -Path $path -Parent } if (!($FileName)) { $FileName = [IO.Path]::GetFileNameWithoutExtension($path) } if (!($Extension)) { if ($IsErrorFile) { $Extension = $ERRFILE_EXT_DEFAULT } else { $Extension = $LOGFILE_EXT_DEFAULT } } return (Join-Path $Directory $FileName) + $Extension } <# .SYNOPSIS Returns stream logging configuration settings. .DESCRIPTION Use this function if you need to use otr display stream logging configuration settings. .PARAMETER Json When set, the settings will be serialized as JSON. .PARAMETER Compress When set, the settings will be serialized in a JSON compact format. .LINK https://github.com/alekdavis/StreamLogging .INPUTS None. .OUTPUTS None. .EXAMPLE $logSettings = Get-LoggingConfig Returns logging configuration settings formatted as an uncompressed JSON string. .EXAMPLE $logSettings = Get-LoggingConfig -Xml -Json Returns logging configuration settings formatted as a compressed XML string. #> function Get-LoggingConfig { [CmdletBinding(DefaultParameterSetName="default")] param ( [Parameter(ParameterSetName="Json")] [switch] $Json, [Parameter(ParameterSetName="Json")] [switch] $Compress ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } if ((-not $Json) -and (-not $Compress)) { return $Script:Config } if ($Compress) { return ($Script:Config | ConvertTo-Json -Compress).Trim() } else { return ($Script:Config | ConvertTo-Json).Trim() } } <# .SYNOPSIS Initializes stream logging. .DESCRIPTION Call this function to configure the StreamLogging module. You can configure logging using the function parameters or a configuration file. You can specify the path to the configuration file via the '-ConfigFile' parameter or use the implicit default path which is named after the running script with the '.StreamLogging.json' extension. For example, if the path to the running script is 'D:\Scripts\MyScript.ps1' the default path to the stream logging configuration file would be 'D:\Scripts\MyScript.ps1.StreamLogging.json'. The configuration file must be in the JSON format similar to the following: { "LogLevel": { "value": "Debug" }, "Console": { "value": true }, "File": { "value": true }, "ErrorFile": { "value": true }, "FilePath": { "value": null }, "ErrorFilePath": { "value": null }, "Backup": { "value": null }, "Overwrite": { "value": true }, "Append": { "value": null }, "WithTimestamp": { "value": true }, "TimestampFormat": { "value": null }, "UtcTime": { "value": true }, "TabSize": { "value": 4 }, "BackgroundColor": { "value": null }, "BackgroundColorError": { "value": null }, "BackgroundColorWarning": { "value": null }, "BackgroundColorInfo": { "value": null }, "BackgroundColorDebug": { "value": null }, "ForegroundColor": { "value": null }, "ForegroundColorError": { "value": null }, "ForegroundColorWarning": { "value": null }, "ForegroundColorInfo": { "value": null }, "ForegroundColorDebug": { "value": "Green" } } You can find a more detailed example of the configuration file at https://github.com/alekdavis/StreamLogging. For details about the configuration file format, see https://github.com/alekdavis/ConfigFile. The configuration file and its elements are optional. A command-line parameter has a higher precedence than the corresponding configuration file value, i.e. if the 'LogLevel' value in the configuration file is set to 'Warning', but the '-LogLevel' function parameter is set to 'Debug', then the log level will be set to 'Debug'. Log levels are ranked from 1 (Error) to 4 (Debug). Setting log level means that all entries with the same or lower ranks will be logged. See the description of the 'LogLevel' parameter for details. Log records can be written to the console and a log file. In addition, error and exception messages can be written to a separate error file. By default, log entries will be written to the console. .PARAMETER LogLevel Defines the maximum level at which the log entries must be written to the console or the log files. The following log level are supported: - None (0): Nothing will be logged. - Error (1): Only errors and exceptions will be logged. - Warning (2): Warnings, errors, and exceptions will be logged. - Info (3): Informational messages will be logged along with warnings, errors, and exceptions. - Debug (4): Debug messages will be logged along with everything else. .PARAMETER Console When set, log entries will be written to the console. If neither the log target switches ('-Console', '-File', and '-ErrorFile') are specified, the '-Console' switch will be automatically turned on (unless the log level is set to 'None'). .PARAMETER File When set, log entries will be written to a log file. This switch will be automatically turned on if the '-FilePath' parameter is set. If the '-FilePath' parameter is not specified, the default log file will be used (the file path will be named after the running script with the '.log' extension, such as 'C:\Script\MyScript.log' for the script 'C:\Script\MyScript.ps1'). The log file will be created only when the first log message is written to it (see the 'Write-Log' function and its derivatives). .PARAMETER ErrorFile When set, error and exception messages will be written to a special error file. This switch will be automatically turned on if the '-ErrorFilePath' parameter is set. If the '-ErrorFilePath' parameter is not specified, the default error file will be used (the file path will be named after the running script with the '.err.log' extension, such as 'C:\Script\MyScript.err.log' for the script 'C:\Script\MyScript.ps1'). The error file will be created only when the first error or exception message is written to it (see the 'Write-Log' function and its derivatives). .PARAMETER FilePath Defines the path to the log file. If not specified, the log file path will be set to the path of the running script, only with the '.log' extension. For example, if the path of the running script is 'C:\Scripts\MyScript.ps1', the default log file path will be 'C:\Scripts\MyScript.log'. You can use the 'Format-LogFilePath' function to customize parts of the log file path. If the '-FilePath' explicitly set, the '-File' switch will be turned on. .PARAMETER ErrorFilePath Defines the path to the error file to which error and exception message will be copied. If not specified, the error file path will be set to the path of the running script, only with the '.err.log' extension. For example, if the path of the running script is 'C:\Scripts\MyScript.ps1', the default error file path will be 'C:\Scripts\MyScript.err.log'. You can use the 'Format-LogFilePath' function to customize parts of the error file path. .PARAMETER Backup When set, the existing log and error files will be backed up (the backed up will contain a timestamp in the file names). This is the default mode (when neither of the old file handling modes is specified). .PARAMETER Overwrite When set, the existing log and error files will be overwritten. .PARAMETER Append When set, the existing log and error files will be appended. .PARAMETER WithLogLevel When set, all messages written to the log and error files (but not to the console) will include their log levels. .PARAMETER WithTimestamp When set, all messages written to the log and error files (but not to the console) will include timestamps. .PARAMETER TimeStampFormat Defines the timestamp format that will be used when the '-WithTimestamp' switch is turned on. The default timestamp format includes year, month, day, hour, minute, and second, such as '2019-10-23 14:45:28'. For formatting details, see .NET documentation ('Custom date and time format strings' at https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings). .PARAMETER UtcTime When set, timestamps will contain time in Universal Time Coordinates (UTC, or GMT). .PARAMETER TabSize Defines the number of indent spaces. The default value is 2. .PARAMETER BackgroundColor Specifies the console background color. When defined, it will be applied to the log entries of all log levels. You can specify individual colors for each log level using the corresponding parameter: BackgroundColorError, BackgroundColorWarning, BackgroundColorInfo, BackgroundColorDebug. .PARAMETER BackgroundColorError Specifies the console background color for error messages. The default value is 'Red'. .PARAMETER BackgroundColorWarning Specifies the console background color for warnings. The default value is 'Yellow'. .PARAMETER BackgroundColorInfo Specifies the console background color for informational messages. .PARAMETER BackgroundColorDebug Specifies the console background color for debug messages. The default value is 'Gray'. .PARAMETER ForegroundColor Specifies the console font color. When defined, it will be applied to the log entries of all log levels. You can specify individual colors for each log level using the corresponding parameter: ForegroundColorError, ForegroundColorWarning, ForegroundColorInfo, ForegroundColorDebug. .PARAMETER ForegroundColorError Specifies the console font color for error messages. The default value is 'Black'. .PARAMETER ForegroundColorWarning Specifies the console font color for warnings. The default value is 'Black'. .PARAMETER ForegroundColorInfo Specifies the console font color for informational messages. .PARAMETER ForegroundColorDebug Specifies the console font color for debug messages. The default value is 'Black'. .PARAMETER ConfigFile Specifies the path or extension of the logging configuration file described above (in the DESCRIPTION section). If no file is found under the path, the parameter value will be appended to the path of the running script. For example, if you set the value to '.Log.config', for the running script with path 'D:\Scripts\MyScript.ps1', the config file path will be formatted as 'D:\Scripts\MyScript.ps1.Log.config'. The default config file path is named after the running script with the '.StreamLogging.json' extension (in our example, it would point to 'D:\Scripts\MyScript.ps1.StreamLogging.json'). If the 'ConfigFile' value is explicitly set, the file with the same path (or extension) must exist. If this parameter is not specified, the file located at the default path is optional. .LINK https://github.com/alekdavis/StreamLogging .INPUTS None. .OUTPUTS None. .EXAMPLE Start-Logging Initializes stream logging to the default settings or the settings specified in the default configuration file. Unless the default settings are overwritten, log messages will be written to the console and the log level will be set to 'Info'. .EXAMPLE Start-Logging -LogLevel None Turns logging off (no log messages will be written anywhere). .EXAMPLE Start-Logging -LogLevel Debug -Console -ErrorFile -WithTime -UtcTime Sets logging for all log levels to be sent to the console. All error and exception messages will be also copied to the default error file. Log entries written to the error file will be prefixed with the timestamps reflecting Universal (GMT) time. .EXAMPLE Start-Logging -ConfigFile ".log.json" Initializes stream logging using the settings from the configuration file named after the running script with the '.log.json' extension. .EXAMPLE Start-Logging -ConfigFile ".log.json" -LogLevel Debug Initializes stream logging using the settings from the configuration file named after the running script with the '.log.json' extension and the 'Debug' log level (regardless of the log level specified in the configuration file). #> function Start-Logging { [CmdletBinding(DefaultParameterSetName="default")] param ( [ValidateSet("None", "Error", "Warning", "Info", "Debug")] [Alias("Log", "Level")] [string] $LogLevel = "Info", [switch] $Console, [switch] $File, [switch] $ErrorFile, [parameter(Position=0)] [string] $FilePath, [parameter(Position=1)] [string] $ErrorFilePath, [Parameter(ParameterSetName="Backup")] [switch] $Backup, [Parameter(ParameterSetName="Overwrite")] [switch] $Overwrite, [Parameter(ParameterSetName="Append")] [switch] $Append, [switch] $WithLogLevel, [switch] $WithTimestamp, [string] $TimestampFormat = "yyyy-MM-dd HH:mm:ss", [Alias("Utc", "Gmt", "GmtTime", "UniversalTime")] [switch] $UtcTime, [ValidateRange(1, 8)] [int] $TabSize = 2, [Parameter(ParameterSetName="BackgroundColorGlobal")] [Parameter(ParameterSetName="ForegroundColorGlobal", Mandatory)] [Parameter(ParameterSetName="ForegroundColorSpecific", Mandatory)] [ValidateSet( "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")] [Alias("Background")] [string] $BackgroundColor, [Parameter(ParameterSetName="BackgroundColorSpecific")] [Parameter(ParameterSetName="ForegroundColorGlobal", Mandatory)] [Parameter(ParameterSetName="ForegroundColorSpecific", Mandatory)] [ValidateSet( "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")] [Alias("BackgroundError")] [string] $BackgroundColorError = "Black", [Parameter(ParameterSetName="BackgroundColorSpecific")] [Parameter(ParameterSetName="ForegroundColorGlobal", Mandatory)] [Parameter(ParameterSetName="ForegroundColorSpecific", Mandatory)] [ValidateSet( "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")] [Alias("BackgroundWarning")] [string] $BackgroundColorWarning = "Black", [Parameter(ParameterSetName="BackgroundColorSpecific")] [Parameter(ParameterSetName="ForegroundColorGlobal", Mandatory)] [Parameter(ParameterSetName="ForegroundColorSpecific", Mandatory)] [ValidateSet( "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")] [Alias("BackgroundInfo")] [string] $BackgroundColorInfo, [Parameter(ParameterSetName="BackgroundColorSpecific")] [Parameter(ParameterSetName="ForegroundColorGlobal", Mandatory)] [Parameter(ParameterSetName="ForegroundColorSpecific", Mandatory)] [ValidateSet( "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")] [Alias("BackgroundDebug")] [string] $BackgroundColorDebug = "Black", [Parameter(ParameterSetName="ForegroundColorGlobal")] [Parameter(ParameterSetName="BackgroundColorGlobal", Mandatory)] [Parameter(ParameterSetName="BackgroundColorSpecific", Mandatory)] [ValidateSet( "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")] [Alias("Foreground")] [string] $ForegroundColor, [Parameter(ParameterSetName="ForegroundColorSpecific")] [Parameter(ParameterSetName="BackgroundColorGlobal", Mandatory)] [Parameter(ParameterSetName="BackgroundColorSpecific", Mandatory)] [ValidateSet( "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")] [Alias("ForegroundError")] [string] $ForegroundColorError = "Red", [Parameter(ParameterSetName="ForegroundColorSpecific")] [Parameter(ParameterSetName="BackgroundColorGlobal", Mandatory)] [Parameter(ParameterSetName="BackgroundColorSpecific", Mandatory)] [ValidateSet( "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")] [Alias("ForegroundWarning")] [string] $ForegroundColorWarning = "Yellow", [Parameter(ParameterSetName="ForegroundColorSpecific")] [Parameter(ParameterSetName="BackgroundColorGlobal", Mandatory)] [Parameter(ParameterSetName="BackgroundColorSpecific", Mandatory)] [ValidateSet( "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")] [Alias("ForegroundInfo")] [string] $ForegroundColorInfo, [Parameter(ParameterSetName="ForegroundColorSpecific")] [Parameter(ParameterSetName="BackgroundColorGlobal", Mandatory)] [Parameter(ParameterSetName="BackgroundColorSpecific", Mandatory)] [ValidateSet( "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")] [Alias("ForegroundDebug")] [string] $ForegroundColorDebug = "Gray", [Alias("Config")] [string] $ConfigFile ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } Write-Verbose "Starting stream logging." # Clear all log config settings. Initialize # Import settings from a config file (if it exists). ImportConfigFile $ConfigFile $PSBoundParameters # NOTE: $Script scope is the scope of this module (not the calling script). # First, check log level. If it is 'None', we're done. if ($LogLevel -eq $LOGLEVEL_NONE) { Write-Verbose "Logging is turned OFF." $Script:Config.LogLevel = $LOGLEVEL_NONE return } $Script:Config.LogLevel = $LogLevel # If neither log targets nor file paths were specified, log to console only. if (!($Console) -and !($File) -and !($ErrorFile) -and !($FilePath) -and !($ErrorFilePath)) { $Script:Config.Console = $true } else { # If log targets were not specified, but file paths were, # set appropriate targets. if (!($Console) -and !($File) -and !($ErrorFile)) { if ($FilePath) { $File = $true } if ($ErrorFilePath) { $ErrorFile = $true } } $Script:Config.Console = [bool]$Console $Script:Config.File = [bool]$File $Script:Config.ErrorFile= [bool]$ErrorFile } # If log file is a log target, but we do not have the path, # set the default path. if ($File -and !($FilePath)) { $path = $null if ($PSCmdlet) { $path = $MyInvocation.PSCommandPath } else { $path = $PSCommandPath } $fileDir = Split-Path -Path $path -Parent $fileName = [IO.Path]::GetFileNameWithoutExtension($path) $FilePath = Format-LogFilePath -Dir $fileDir -Name $fileName } $Script:Config.FilePath = $FilePath # If error file is a log target, but we do not have the path, # set the default path. if ($ErrorFile -and !($ErrorFilePath)) { $path = $null if ($PSCmdlet) { $path = $MyInvocation.PSCommandPath } else { $path = $PSCommandPath } $fileDir = Split-Path -Path $path -Parent $fileName = [IO.Path]::GetFileNameWithoutExtension($path) $ErrorFilePath = Format-LogFilePath -Dir $fileDir -Name $fileName -IsErrorFile } $Script:Config.ErrorFilePath = $ErrorFilePath # Define what we'll do with existing files (back them up by default). if (!($Backup) -and !($Overwrite) -and !($Append)) { $Backup = $true } if ($Backup) { $Script:Config.Backup = $true } elseif ($Overwrite) { $Script:Config.Overwrite = $true } else { $Script:Config.Append = $true } $Script:Config.UtcTime = [bool]$UtcTime $Script:Config.TabSize = $TabSize $Script:Config.WithLogLevel = $WithLogLevel $Script:Config.WithTimestamp = $WithTimestamp $Script:Config.TimestampFormat = $TimestampFormat # Verify timestamp. if ($TimestampFormat) { try { if ((Get-Date).ToString($TimestampFormat)) { $Script:Config.TimestampFormat = $TimestampFormat } else { throw "Cannot convert timestamp to string." } } catch { throw (New-Object System.Exception( "Invalid timestamp format: " + $TimestampFormat + ".", $_.Exception)) } } # Define console foreground colors. if ($ForegroundColor) { # If a single color is specified, apply it to everything. $Script:Config.ForegroundColor = $ForegroundColor } else { $Colors = @{ $LOGLEVEL_ERROR = $ForegroundColorError $LOGLEVEL_WARNING = $ForegroundColorWarning $LOGLEVEL_INFO = $ForegroundColorInfo $LOGLEVEL_DEBUG = $ForegroundColorDebug } foreach ($key in $Colors.Keys) { $color = $Colors[$key] if ($color) { $Script:ForegroundColors[$key] = $color } } } # Define console background colors. if ($BackgroundColor) { $Script:Config.BackgroundColor = $BackgroundColor } else { $Colors = @{ $LOGLEVEL_ERROR = $BackgroundColorError $LOGLEVEL_WARNING = $BackgroundColorWarning $LOGLEVEL_INFO = $BackgroundColorInfo $LOGLEVEL_DEBUG = $BackgroundColorDebug } foreach ($key in $Colors.Keys) { $color = $Colors[$key] if ($color) { $Script:BackgroundColors[$key] = $color } } } $Script:Config.Initialized = $true } <# .SYNOPSIS Resets stream logging and releases all resources. .DESCRIPTION Call this function to perform a cleanup after the last log entry was written. It will close any open file streams and reset configuration settings to the default values. If you are only logging to the console, you do not need to call this function (altough, it would not hurt). .LINK https://github.com/alekdavis/StreamLogging .INPUTS None. .OUTPUTS None. .EXAMPLE Stop-Logging Closes log files (if any were previously open) and resets all logging settings to the defaults. #> function Stop-Logging { [CmdletBinding()] param ( ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } Write-Verbose "Stopping stream logging." Initialize } <# .SYNOPSIS Checks if logging was initialized. .DESCRIPTION Call this function to check whether you need to call Stop-Logging to uninitialize resources. .LINK https://github.com/alekdavis/StreamLogging .INPUTS None. .OUTPUTS None. .EXAMPLE if (Test-LoggingStarted) Stop-Logging Checks if logging started and if so calls Stop-Logging to close allocated resources. #> function Test-LoggingStarted { [CmdletBinding()] param ( ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } return $Script:Config.Initialized } <# .SYNOPSIS Writes a log entry. .DESCRIPTION Call this function or one of its shortcuts (Write-LogDebug, Write-LogError, Write-LogException, Write-LogInfo, Write-LogWarning) to write a log message or exception info to the configured log targets: console, log file, and/or error file. Before calling this function, make sure that 'Start-Logging' is called to initialize log settings. .PARAMETER LogLevel Defines the log level of the current message. If not specified, the default log level will be 'Info', unless exception is being logged, in which case, it will be 'Error'. .PARAMETER Message Defines the message that will being logged. The value can be passed via this parameter or as a piped input. .PARAMETER Errors Used for logging exceptions. By default, it will hold the '$Global:Error' (a collection of session errors) object, but you can also pass it (or any of its derivatives, such as the '$_' object in the exception catch block, although, in this case, you'll lose inner exceptions) explicitly. You can use it to pass your own error or collection of errors, but make sure that each object either is or contains a valid exception (in the latter case, an exception must be set to the 'Exception' property). .PARAMETER Indent Specifies by how many tabs (see the 'Start-Logging' function description) the log entry must be indented. The default value is 0 (zero). The maximum value is 255. .PARAMETER NoConsole When set, the log entry will not be written to the console even if the console was set as a log target by the 'Start-Logging' function. .PARAMETER NoFile When set, the log entry will not be written to the log and/or error files even if they were set as the log targets by the 'Start-Logging' function. .PARAMETER Raw When set, the value of the '-Errors' parameter will be written using the default serialization (by default, only error messages from all errors in the collection will be logged without any additional exception data). .PARAMETER Object Use this parameter to log an object serialized as a JSON string. .PARAMETER Compress When logging an object, use this parameter to serialize it in a compact format. .LINK https://github.com/alekdavis/StreamLogging .INPUTS A string message object ('Message' parameter) can be piped into this function. .OUTPUTS None. .EXAMPLE Write-Log "Hello, info!" Writes an informational message to the configured log targets. .EXAMPLE Write-Log -Message "Hello, info!" Writes an informational message to the configured log targets. .EXAMPLE Write-Log -Message "Hello, info!" -LogLevel Info Writes an informational message to the configured log targets. .EXAMPLE "Hello, info!" | Write-Log -NoFile Writes an informational message to the configured log targets, except the log file, even if it is one of the configured log targets. .EXAMPLE Write-Log "Hello, debug!" -LogLevel Debug -Indent 1 Writes an debug message to the configured log targets indenting it by one tab. .EXAMPLE Write-Log "Hello, warning!" -LogLevel Warning -NoConsole Writes an warning message to the configured log targets, except the console, even if it is one of the configured log targets. .EXAMPLE Write-Log "Hello, error!" -LogLevel Error Writes an error message to the configured log targets. If the '$Global:Error' object contains errors, they will be logged as well (only exception messages from the error object will be logged). .EXAMPLE "Hello, error!" | Write-Log -LogLevel Error -Errors $Global:Error -Raw Writes an error message to the configured log targets along with the explicitly passed errors from the '$Global:Error' object. The errors will be serialized using the default formatting. #> function Write-Log { [CmdletBinding(DefaultParameterSetName="Message")] param ( [ValidateSet("Error", "Warning", "Info", "Debug")] [Alias("Log", "Level")] [string] $LogLevel = "Info", [Parameter(Position=0,ValueFromPipeline)] [string] $Message, [object] $Errors = $Global:Error, [Parameter(Position=1)] [ValidateRange(0, 255)] [int] $Indent = 0, [switch] $NoConsole, [switch] $NoFile, [switch] $Raw, [object] $Object, [switch] $Compress ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } if ($NoConsole -and $NoFile) { return } $params = @{} # Set common parameters. if ($Indent -gt 0) { $params.Add("Indent", $Indent) } if ($NoConsole) { $params.Add("NoConsole", $true) } if ($NoFile) { $params.Add("NoFile", $true) } # Add object info, if one was specified. if ($PSBoundParameters.ContainsKey("Object") -and ($null -ne $Object)) { $params.Add("Object", $Object) if ($Compress) { $params.Add("Compress", $true) } } if ($PSBoundParameters.ContainsKey("Message") -or ($Message)) { $params.Add("Message", $Message) } switch ($LogLevel) { $LOGLEVEL_ERROR { # If we have a message, log it first. if ($PSBoundParameters.ContainsKey("Message") -or ($Message)) { Write-LogError @params $params.Remove("Message") if ($params.ContainsKey("Object")) { $params.Remove("Object") } } if ($params.ContainsKey("Object")) { Write-LogError @params $params.Remove("Object") } # If we have session errors, log them as well. if ($Errors) { $params.Add("Errors", $Errors) if ($Raw) { $params.Add("Raw", $true) } Write-LogException @params } break; } $LOGLEVEL_WARNING { Write-LogWarning @params break } $LOGLEVEL_INFO { Write-LogInfo @params break } default { Write-LogDebug @params break } } } <# .SYNOPSIS Writes a debug log entry. .DESCRIPTION Call this function to write a debug message to the configured log targets: console or log file. Before calling this function, make sure that 'Start-Logging' is called to initialize log settings. .PARAMETER Message Defines the message that will being logged. The value can be passed via this parameter or as a piped input. .PARAMETER Indent Specifies by how many tabs (see the 'Start-Logging' function description) the log entry must be indented. The default value is 0 (zero). The maximum value is 255. .PARAMETER NoConsole When set, the log entry will not be written to the console even if the console was set as a log target by the 'Start-Logging' function. .PARAMETER NoFile When set, the log entry will not be written to the log file even if it was set as a log target by the 'Start-Logging' function. .PARAMETER Object Use this parameter to log an object serialized as a JSON string. .PARAMETER Compress When logging an object, use this parameter to serialize it in a compact format. .LINK https://github.com/alekdavis/StreamLogging .INPUTS A string message object ('Message' parameter) can be piped into this function. .OUTPUTS None. .EXAMPLE Write-LogDebug "Hello, debug!" Writes a debug message to the configured log targets. .EXAMPLE "Hello, debug!" | Write-LogDebug Writes a debug message to the configured log targets. .EXAMPLE Write-LogDebug "Hello, debug!" -Indent 1 Writes a debug message to the configured log targets indenting it by one tab. .EXAMPLE Write-LogDebug "Hello, debug!" -NoFile Writes a debug message to the console only, assuming that it is a configured log target. .EXAMPLE "Hello, debug!" | Write-LogDebug -NoConsole Writes a debug message to the log file only, assuming that it is a configured log target. #> function Write-LogDebug { [CmdletBinding(DefaultParameterSetName="default")] param ( [Parameter(Position=0,ValueFromPipeline)] [string] $Message, [Parameter(Position=1)] [ValidateRange(0, 255)] [int] $Indent = 0, [Parameter(Position=2)] [switch] $NoConsole, [Parameter(Position=3)] [switch] $NoFile, [object] $Object, [switch] $Compress ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } if ($NoConsole -and $NoFile) { return } # Log message (if we have one). if ($PSBoundParameters.ContainsKey("Message") -and ($null -ne $Message)) { WriteLog $LOGLEVEL_DEBUG $Message $Indent (-not $NoConsole) (-not $NoFile) } # Log object (if we have one). if (-not $PSBoundParameters.ContainsKey("Object")) { return } $Message = $null if ($Compress) { $Message = ($Object | ConvertTo-Json -Compress).Trim() } else { $Message = ($Object | ConvertTo-Json).Trim() } if ($null -ne $Message) { WriteLog $LOGLEVEL_DEBUG $Message $Indent (-not $NoConsole) (-not $NoFile) } } <# .SYNOPSIS Writes an error log entry. .DESCRIPTION Call this function to write an error message to the configured log targets: console, log file, and/or error file. Before calling this function, make sure that 'Start-Logging' is called to initialize log settings. .PARAMETER Message Defines the message that will being logged. The value can be passed via this parameter or as a piped input. .PARAMETER Indent Specifies by how many tabs (see the 'Start-Logging' function description) the log entry must be indented. The default value is 0 (zero). The maximum value is 255. .PARAMETER NoConsole When set, the log entry will not be written to the console even if the console was set as a log target by the 'Start-Logging' function. .PARAMETER NoFile When set, the log entry will not be written to the log and/or error files even if they were set as the log targets by the 'Start-Logging' function. .PARAMETER Object Use this parameter to log an object serialized as a JSON string. .PARAMETER Compress When logging an object, use this parameter to serialize it in a compact format. .LINK https://github.com/alekdavis/StreamLogging .INPUTS A string message object ('Message' parameter) can be piped into this function. .OUTPUTS None. .EXAMPLE Write-LogError "Hello, error!" Writes an error message to the configured log targets. .EXAMPLE "Hello, error!" | Write-LogError Writes an error message to the configured log targets. .EXAMPLE Write-LogError "Hello, error!" -Indent 1 Writes an error message to the configured log targets indenting it by one tab. .EXAMPLE Write-LogError "Hello, error!" -NoFile Writes an error message to the console only, assuming that it is a configured log target. .EXAMPLE "Hello, error!" | Write-LogError -NoConsole Writes an error message to the log and error files only, assuming that they are configured as the log targets. #> function Write-LogError { [CmdletBinding()] param ( [Parameter(Position=0,ValueFromPipeline)] [string] $Message, [Parameter(Position=1)] [ValidateRange(0, 255)] [int] $Indent = 0, [Parameter(Position=2)] [switch] $NoConsole, [Parameter(Position=3)] [switch] $NoFile, [object] $Object, [switch] $Compress ) if ($NoConsole -and $NoFile) { return } # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } # Log message (if we have one). if ($PSBoundParameters.ContainsKey("Message") -and ($null -ne $Message)) { WriteLog $LOGLEVEL_ERROR $Message $Indent (-not $NoConsole) (-not $NoFile) } # Log object (if we have one). if (-not $PSBoundParameters.ContainsKey("Object")) { return } $Message = $null if ($Compress) { $Message = ($Object | ConvertTo-Json -Compress).Trim() } else { $Message = ($Object | ConvertTo-Json).Trim() } if ($null -ne $Message) { WriteLog $LOGLEVEL_ERROR $Message $Indent (-not $NoConsole) (-not $NoFile) } } <# .SYNOPSIS Writes a log entry from the information in the error object. .DESCRIPTION Call this function to write an error message to the configured log targets: console, log file, and/or error file. Before calling this function, make sure that 'Start-Logging' is called to initialize log settings. .PARAMETER Errors If not explicitly set, this parameter will hold the value of the '$Global:Error' object. You can use it to pass your own error or collection of errors, but make sure that each object either is or contains a valid exception (in the latter case, an exception must be set to the 'Exception' property). The value can be passed via this parameter or as a piped input. .PARAMETER Indent Specifies by how many tabs (see the 'Start-Logging' function description) the log entry must be indented. The default value is 0 (zero). The maximum value is 255. .PARAMETER NoConsole When set, the log entry will not be written to the console even if the console was set as a log target by the 'Start-Logging' function. .PARAMETER NoFile When set, the log entry will not be written to the log and/or error files even if they were set as the log targets by the 'Start-Logging' function. .PARAMETER Raw When set, the value of the '-Errors' parameter will be written using the default serialization (by default, only error messages from all errors in the collection will be logged without any additional exception data). .LINK https://github.com/alekdavis/StreamLogging .INPUTS An error collection object ('Errors' parameter) can be piped into this function. .OUTPUTS None. .EXAMPLE Write-LogException Writes error messages from the '$Global:Error' collection to the configured log targets. .EXAMPLE Write-LogException -Errors $Global:Error Writes error messages from the '$Global:Error' collection to the configured log targets. .EXAMPLE $Global:Error | Write-LogException -Raw Writes error info from the '$Global:Error' collection to the configured log targets using the default error serialization. .EXAMPLE Write-LogException -Indent 1 Writes error messages from the '$Global:Error' collection to the configured log targets indenting them by one tab. .EXAMPLE Write-LogException -NoFile Writes error messages from the '$Global:Error' collection to the console only, assuming that it is a configured log target. .EXAMPLE "Hello, error!" | Write-LogError -NoConsole Writes error messages from the '$Global:Error' collection to the log and error files only, assuming that they are configured as the log targets. #> function Write-LogException { [CmdletBinding()] param ( [Parameter(Position=0,ValueFromPipeline)] [object] $Errors = $Global:Error, [Parameter(Position=1)] [ValidateRange(0, 255)] [int] $Indent = 0, [Parameter(Position=2)] [switch] $NoConsole, [Parameter(Position=3)] [switch] $NoFile, [Parameter(Position=4)] [switch] $Raw ) if ($NoConsole -and $NoFile) { return } # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } $message = $null if ($Raw) { $message = ($Errors | Out-String).Trim() if ($message) { Write-LogError $message $Indent $NoConsole $NoFile } } else { if ($Errors.Count) { foreach ($err in $Errors) { $message = $null; # Try getting error from the global $Errors object. if ($err.Exception -and $err.Exception.Message) { $message = FormatError $err.Exception } # Or maybe it is an exception object already. elseif ($err.Message) { $message = FormatError $err } # Forget it. else { $message = $err.ToString().Trim() } if ($message) { Write-LogError -Message $message $Indent $NoConsole $NoFile } } } else { # Try getting error from the global $Errors object. if ($Errors.Exception -and $Errors.Exception.Message) { $message = FormatError $Errors.Exception } # Or maybe it is an exception object already. elseif ($Errors.Message) { $message = FormatError $Errors } # Forget it. else { $message = $Errors.ToString().Trim() } if ($message) { Write-LogError -Message $message $Indent $NoConsole } } } } <# .SYNOPSIS Writes an informational log entry. .DESCRIPTION Call this function to write an informational message to the configured log targets: console or log file. Before calling this function, make sure that 'Start-Logging' is called to initialize log settings. .PARAMETER Message Defines the message that will being logged. The value can be passed via this parameter or as a piped input. .PARAMETER Indent Specifies by how many tabs (see the 'Start-Logging' function description) the log entry must be indented. The default value is 0 (zero). The maximum value is 255. .PARAMETER NoConsole When set, the log entry will not be written to the console even if the console was set as a log target by the 'Start-Logging' function. .PARAMETER NoFile When set, the log entry will not be written to the log file even if it was set as a log target by the 'Start-Logging' function. .PARAMETER Object Use this parameter to log an object serialized as a JSON string. .PARAMETER Compress When logging an object, use this parameter to serialize it in a compact format. .LINK https://github.com/alekdavis/StreamLogging .INPUTS A string message object ('Message' parameter) can be piped into this function. .OUTPUTS None. .EXAMPLE Write-LogInfo "Hello, info!" Writes an informational message to the configured log targets. .EXAMPLE "Hello, info!" | Write-LogInfo Writes an informational message to the configured log targets. .EXAMPLE Write-LogInfo "Hello, info!" -Indent 1 Writes an informational message to the configured log targets indenting it by one tab. .EXAMPLE Write-LogInfo "Hello, info!" -NoFile Writes an informational message to the console only, assuming that it is a configured log target. .EXAMPLE "Hello, info!" | Write-LogInfo -NoConsole Writes an informational message to the log file only, assuming that it is a configured log target. #> function Write-LogInfo { [CmdletBinding()] param ( [Parameter(Position=0,ValueFromPipeline)] [string] $Message, [Parameter(Position=1)] [ValidateRange(0, 255)] [int] $Indent = 0, [Parameter(Position=2)] [switch] $NoConsole, [Parameter(Position=3)] [switch] $NoFile, [object] $Object, [switch] $Compress ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } if ($NoConsole -and $NoFile) { return } # Log message (if we have one). if ($PSBoundParameters.ContainsKey("Message") -and ($null -ne $Message)) { WriteLog $LOGLEVEL_INFO $Message $Indent (-not $NoConsole) (-not $NoFile) } # Log object (if we have one). if (-not $PSBoundParameters.ContainsKey("Object")) { return } $Message = $null if ($Compress) { $Message = ($Object | ConvertTo-Json -Compress).Trim() } else { $Message = ($Object | ConvertTo-Json).Trim() } if ($null -ne $Message) { WriteLog $LOGLEVEL_INFO $Message $Indent (-not $NoConsole) (-not $NoFile) } } <# .SYNOPSIS Writes a warning log entry. .DESCRIPTION Call this function to write a warning message to the configured log targets: console or log file. Before calling this function, make sure that 'Start-Logging' is called to initialize log settings. .PARAMETER Message Defines the message that will being logged. The value can be passed via this parameter or as a piped input. .PARAMETER Indent Specifies by how many tabs (see the 'Start-Logging' function description) the log entry must be indented. The default value is 0 (zero). The maximum value is 255. .PARAMETER NoConsole When set, the log entry will not be written to the console even if the console was set as a log target by the 'Start-Logging' function. .PARAMETER NoFile When set, the log entry will not be written to the log file even if it was set as a log target by the 'Start-Logging' function. .PARAMETER Object Use this parameter to log an object serialized as a JSON string. .PARAMETER Compress When logging an object, use this parameter to serialize it in a compact format. .LINK https://github.com/alekdavis/StreamLogging .INPUTS A string message object ('Message' parameter) can be piped into this function. .OUTPUTS None. .EXAMPLE Write-LogWarning "Hello, warning!" Writes a warning message to the configured log targets. .EXAMPLE "Hello, warning!" | Write-LogWarning Writes a warning message to the configured log targets. .EXAMPLE Write-LogWarning "Hello, warning!" -Indent 1 Writes a warning message to the configured log targets indenting it by one tab. .EXAMPLE Write-LogWarning "Hello, warning!" -NoFile Writes a warning message to the console only, assuming that it is a configured log target. .EXAMPLE "Hello, warning!" | Write-LogWarning -NoConsole Writes a warning message to the log file only, assuming that it is a configured log target. #> function Write-LogWarning { [CmdletBinding()] param ( [Parameter(Position=0,ValueFromPipeline)] [string] $Message, [Parameter(Position=1)] [ValidateRange(0, 255)] [int] $Indent = 0, [Parameter(Position=2)] [switch] $NoConsole, [Parameter(Position=3)] [switch] $NoFile, [object] $Object, [switch] $Compress ) # Allow module to inherit '-Verbose' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Verbose')))) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } # Allow module to inherit '-Debug' flag. if (($PSCmdlet) -and (!($PSBoundParameters.ContainsKey('Debug')))) { $DebugPreference = $PSCmdlet.GetVariableValue('DebugPreference') } if ($NoConsole -and $NoFile) { return } # Log message (if we have one). if ($PSBoundParameters.ContainsKey("Message") -and ($null -ne $Message)) { WriteLog $LOGLEVEL_WARNING $Message $Indent (-not $NoConsole) (-not $NoFile) } # Log object (if we have one). if (-not $PSBoundParameters.ContainsKey("Object")) { return } $Message = $null if ($Compress) { $Message = ($Object | ConvertTo-Json -Compress).Trim() } else { $Message = ($Object | ConvertTo-Json).Trim() } if ($null -ne $Message) { WriteLog $LOGLEVEL_WARNING $Message $Indent (-not $NoConsole) (-not $NoFile) } } Export-ModuleMember -Function "*-*" |