Colors in JavaScript console
Asked Answered
P

30

1210

Can Chrome's built-in JavaScript console display colors?

I want errors in red, warnings in orange and console.log's in green. Is that possible?

Pearman answered 21/9, 2011 at 19:36 Comment(5)
You can get errors in red (the default) simply by using console.error() instead of console.log...Welby
console.warn() is also available with an orange 'warning' icon, although the text itself is still black.Firestone
console.log("%c", "background: red;padding: 100000px;"); will cause very weird behavior in Chrome, especially when scrolling the console.Endocranium
An easy/simplest way do it to show colors in consoleEdgardoedge
I wrote a tiny package for coloring logs: console colorsI
M
1842

In Chrome & Firefox (+31) you can add CSS in console.log messages:

console.log('%c Oh my heavens! ', 'background: #222; color: #bada55');

Console color example in Chrome

The same can be applied for adding multiple CSS to same command. syntax for multi coloring chrome console messages

References

Mexicali answered 22/10, 2012 at 18:22 Comment(25)
Apparently, Firebug has supported this for a long time.Plebiscite
To use HTML span elements to style different portions of a console.log message, check out this code: jsfiddle.net/yg6hk/5Lenten
this doesn't allow to use multiple arguments to console.logWegner
But why after color output give "undefined" message ?Benempt
Notably in node.js modules, there's a slicker api for the same purpose. github.com/medikoo/cli-color github.com/marak/colors.jsPargeting
@AshwinP: All console commands show the output followed by the return value. The console command returns no value, therefore you will see 'undefined'. This is normal, expected behavior and occurs whenever you run any command in the console which has no return value.Katheleenkatherin
@TNguyen Can we add multiple colors in console command? is it correct way to add? console.log('%c Oh my %c heavens! ', 'background: #222; color: #bada55', 'background: #222; color: #ff0000','more text');Benempt
@AshwinP, You can't do it like that but check out Hans' jsFiddle for an example of a custom solution.Katheleenkatherin
Why stop at just coloring the text? Let's put some images into the console too: console.log('%c', 'padding:28px 119px;line-height:100px;background:url(http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=6) no-repeat;');Warmblooded
this is best: background: #444; color: #bada55; padding: 2px; border-radius:2px its all about the border-radiusOnwards
Any way to do this with console.time() and console.TimeEnd()?Bradstreet
And how to CSS only a single word? UPD: just pass the empty string css after the word.Sanitary
How about this? console.log = function(){ /* Hello! */ };Dehart
Firefox supports colours on the console natively now (without firebug), with the same syntax, you may want to update your answer to reflect thatProtuberance
OH MY GOD, that's so fancy, I feel like a Starbucks chick getting a Frappu-cci-no!Yachting
Is it possible to color multilines?Lodovico
How do you detect support for this feature in a browser? #40428739Ostia
thanks @Nakilon! console.log('default styling %cStyled Text%c back to default styling', 'font-style: italic', '')Wier
@Lodovico use \n in your string console.log('%cline 1\n%cline 2', 'color: red', 'color: green')Wier
And what if user open site wit IE? It will continue to work or?.. I remeber I had problems when IE was breaking my site when console object was missing. So now I always do this after use 'strict': if (!window.console) window.console = {}; if (!window.console.log) window.console.log = function () { };Smutch
Yeah firefox supports non-important stuff.Hijoung
Print Google with the colors: console.log('%cG'+'%co'+'%co'+'%cg'+'%cl'+'%ce', 'color: #4286f5;', 'color: #ea4235;', 'color: #fabc05;', 'color: #4286f5;', 'color: #34a853;', 'color: #ea4235;');Norsworthy
The link is not working anymore. The latest source which is independent of the type of a browser is here: console - Web APIs | MDNClinkstone
okay , how do i add some padding and margin-top , just kidding !Dunkle
To be clear, the +'s do nothing. I don't know why everyone is writing "%cfoo"+"%cbar" - you can just write "%cfoo%cbar".Ceiba
S
697

Here is an extreme example with rainbow drop shadow.

var css = "text-shadow: -1px -1px hsl(0,100%,50%), 1px 1px hsl(5.4, 100%, 50%), 3px 2px hsl(10.8, 100%, 50%), 5px 3px hsl(16.2, 100%, 50%), 7px 4px hsl(21.6, 100%, 50%), 9px 5px hsl(27, 100%, 50%), 11px 6px hsl(32.4, 100%, 50%), 13px 7px hsl(37.8, 100%, 50%), 14px 8px hsl(43.2, 100%, 50%), 16px 9px hsl(48.6, 100%, 50%), 18px 10px hsl(54, 100%, 50%), 20px 11px hsl(59.4, 100%, 50%), 22px 12px hsl(64.8, 100%, 50%), 23px 13px hsl(70.2, 100%, 50%), 25px 14px hsl(75.6, 100%, 50%), 27px 15px hsl(81, 100%, 50%), 28px 16px hsl(86.4, 100%, 50%), 30px 17px hsl(91.8, 100%, 50%), 32px 18px hsl(97.2, 100%, 50%), 33px 19px hsl(102.6, 100%, 50%), 35px 20px hsl(108, 100%, 50%), 36px 21px hsl(113.4, 100%, 50%), 38px 22px hsl(118.8, 100%, 50%), 39px 23px hsl(124.2, 100%, 50%), 41px 24px hsl(129.6, 100%, 50%), 42px 25px hsl(135, 100%, 50%), 43px 26px hsl(140.4, 100%, 50%), 45px 27px hsl(145.8, 100%, 50%), 46px 28px hsl(151.2, 100%, 50%), 47px 29px hsl(156.6, 100%, 50%), 48px 30px hsl(162, 100%, 50%), 49px 31px hsl(167.4, 100%, 50%), 50px 32px hsl(172.8, 100%, 50%), 51px 33px hsl(178.2, 100%, 50%), 52px 34px hsl(183.6, 100%, 50%), 53px 35px hsl(189, 100%, 50%), 54px 36px hsl(194.4, 100%, 50%), 55px 37px hsl(199.8, 100%, 50%), 55px 38px hsl(205.2, 100%, 50%), 56px 39px hsl(210.6, 100%, 50%), 57px 40px hsl(216, 100%, 50%), 57px 41px hsl(221.4, 100%, 50%), 58px 42px hsl(226.8, 100%, 50%), 58px 43px hsl(232.2, 100%, 50%), 58px 44px hsl(237.6, 100%, 50%), 59px 45px hsl(243, 100%, 50%), 59px 46px hsl(248.4, 100%, 50%), 59px 47px hsl(253.8, 100%, 50%), 59px 48px hsl(259.2, 100%, 50%), 59px 49px hsl(264.6, 100%, 50%), 60px 50px hsl(270, 100%, 50%), 59px 51px hsl(275.4, 100%, 50%), 59px 52px hsl(280.8, 100%, 50%), 59px 53px hsl(286.2, 100%, 50%), 59px 54px hsl(291.6, 100%, 50%), 59px 55px hsl(297, 100%, 50%), 58px 56px hsl(302.4, 100%, 50%), 58px 57px hsl(307.8, 100%, 50%), 58px 58px hsl(313.2, 100%, 50%), 57px 59px hsl(318.6, 100%, 50%), 57px 60px hsl(324, 100%, 50%), 56px 61px hsl(329.4, 100%, 50%), 55px 62px hsl(334.8, 100%, 50%), 55px 63px hsl(340.2, 100%, 50%), 54px 64px hsl(345.6, 100%, 50%), 53px 65px hsl(351, 100%, 50%), 52px 66px hsl(356.4, 100%, 50%), 51px 67px hsl(361.8, 100%, 50%), 50px 68px hsl(367.2, 100%, 50%), 49px 69px hsl(372.6, 100%, 50%), 48px 70px hsl(378, 100%, 50%), 47px 71px hsl(383.4, 100%, 50%), 46px 72px hsl(388.8, 100%, 50%), 45px 73px hsl(394.2, 100%, 50%), 43px 74px hsl(399.6, 100%, 50%), 42px 75px hsl(405, 100%, 50%), 41px 76px hsl(410.4, 100%, 50%), 39px 77px hsl(415.8, 100%, 50%), 38px 78px hsl(421.2, 100%, 50%), 36px 79px hsl(426.6, 100%, 50%), 35px 80px hsl(432, 100%, 50%), 33px 81px hsl(437.4, 100%, 50%), 32px 82px hsl(442.8, 100%, 50%), 30px 83px hsl(448.2, 100%, 50%), 28px 84px hsl(453.6, 100%, 50%), 27px 85px hsl(459, 100%, 50%), 25px 86px hsl(464.4, 100%, 50%), 23px 87px hsl(469.8, 100%, 50%), 22px 88px hsl(475.2, 100%, 50%), 20px 89px hsl(480.6, 100%, 50%), 18px 90px hsl(486, 100%, 50%), 16px 91px hsl(491.4, 100%, 50%), 14px 92px hsl(496.8, 100%, 50%), 13px 93px hsl(502.2, 100%, 50%), 11px 94px hsl(507.6, 100%, 50%), 9px 95px hsl(513, 100%, 50%), 7px 96px hsl(518.4, 100%, 50%), 5px 97px hsl(523.8, 100%, 50%), 3px 98px hsl(529.2, 100%, 50%), 1px 99px hsl(534.6, 100%, 50%), 7px 100px hsl(540, 100%, 50%), -1px 101px hsl(545.4, 100%, 50%), -3px 102px hsl(550.8, 100%, 50%), -5px 103px hsl(556.2, 100%, 50%), -7px 104px hsl(561.6, 100%, 50%), -9px 105px hsl(567, 100%, 50%), -11px 106px hsl(572.4, 100%, 50%), -13px 107px hsl(577.8, 100%, 50%), -14px 108px hsl(583.2, 100%, 50%), -16px 109px hsl(588.6, 100%, 50%), -18px 110px hsl(594, 100%, 50%), -20px 111px hsl(599.4, 100%, 50%), -22px 112px hsl(604.8, 100%, 50%), -23px 113px hsl(610.2, 100%, 50%), -25px 114px hsl(615.6, 100%, 50%), -27px 115px hsl(621, 100%, 50%), -28px 116px hsl(626.4, 100%, 50%), -30px 117px hsl(631.8, 100%, 50%), -32px 118px hsl(637.2, 100%, 50%), -33px 119px hsl(642.6, 100%, 50%), -35px 120px hsl(648, 100%, 50%), -36px 121px hsl(653.4, 100%, 50%), -38px 122px hsl(658.8, 100%, 50%), -39px 123px hsl(664.2, 100%, 50%), -41px 124px hsl(669.6, 100%, 50%), -42px 125px hsl(675, 100%, 50%), -43px 126px hsl(680.4, 100%, 50%), -45px 127px hsl(685.8, 100%, 50%), -46px 128px hsl(691.2, 100%, 50%), -47px 129px hsl(696.6, 100%, 50%), -48px 130px hsl(702, 100%, 50%), -49px 131px hsl(707.4, 100%, 50%), -50px 132px hsl(712.8, 100%, 50%), -51px 133px hsl(718.2, 100%, 50%), -52px 134px hsl(723.6, 100%, 50%), -53px 135px hsl(729, 100%, 50%), -54px 136px hsl(734.4, 100%, 50%), -55px 137px hsl(739.8, 100%, 50%), -55px 138px hsl(745.2, 100%, 50%), -56px 139px hsl(750.6, 100%, 50%), -57px 140px hsl(756, 100%, 50%), -57px 141px hsl(761.4, 100%, 50%), -58px 142px hsl(766.8, 100%, 50%), -58px 143px hsl(772.2, 100%, 50%), -58px 144px hsl(777.6, 100%, 50%), -59px 145px hsl(783, 100%, 50%), -59px 146px hsl(788.4, 100%, 50%), -59px 147px hsl(793.8, 100%, 50%), -59px 148px hsl(799.2, 100%, 50%), -59px 149px hsl(804.6, 100%, 50%), -60px 150px hsl(810, 100%, 50%), -59px 151px hsl(815.4, 100%, 50%), -59px 152px hsl(820.8, 100%, 50%), -59px 153px hsl(826.2, 100%, 50%), -59px 154px hsl(831.6, 100%, 50%), -59px 155px hsl(837, 100%, 50%), -58px 156px hsl(842.4, 100%, 50%), -58px 157px hsl(847.8, 100%, 50%), -58px 158px hsl(853.2, 100%, 50%), -57px 159px hsl(858.6, 100%, 50%), -57px 160px hsl(864, 100%, 50%), -56px 161px hsl(869.4, 100%, 50%), -55px 162px hsl(874.8, 100%, 50%), -55px 163px hsl(880.2, 100%, 50%), -54px 164px hsl(885.6, 100%, 50%), -53px 165px hsl(891, 100%, 50%), -52px 166px hsl(896.4, 100%, 50%), -51px 167px hsl(901.8, 100%, 50%), -50px 168px hsl(907.2, 100%, 50%), -49px 169px hsl(912.6, 100%, 50%), -48px 170px hsl(918, 100%, 50%), -47px 171px hsl(923.4, 100%, 50%), -46px 172px hsl(928.8, 100%, 50%), -45px 173px hsl(934.2, 100%, 50%), -43px 174px hsl(939.6, 100%, 50%), -42px 175px hsl(945, 100%, 50%), -41px 176px hsl(950.4, 100%, 50%), -39px 177px hsl(955.8, 100%, 50%), -38px 178px hsl(961.2, 100%, 50%), -36px 179px hsl(966.6, 100%, 50%), -35px 180px hsl(972, 100%, 50%), -33px 181px hsl(977.4, 100%, 50%), -32px 182px hsl(982.8, 100%, 50%), -30px 183px hsl(988.2, 100%, 50%), -28px 184px hsl(993.6, 100%, 50%), -27px 185px hsl(999, 100%, 50%), -25px 186px hsl(1004.4, 100%, 50%), -23px 187px hsl(1009.8, 100%, 50%), -22px 188px hsl(1015.2, 100%, 50%), -20px 189px hsl(1020.6, 100%, 50%), -18px 190px hsl(1026, 100%, 50%), -16px 191px hsl(1031.4, 100%, 50%), -14px 192px hsl(1036.8, 100%, 50%), -13px 193px hsl(1042.2, 100%, 50%), -11px 194px hsl(1047.6, 100%, 50%), -9px 195px hsl(1053, 100%, 50%), -7px 196px hsl(1058.4, 100%, 50%), -5px 197px hsl(1063.8, 100%, 50%), -3px 198px hsl(1069.2, 100%, 50%), -1px 199px hsl(1074.6, 100%, 50%), -1px 200px hsl(1080, 100%, 50%), 1px 201px hsl(1085.4, 100%, 50%), 3px 202px hsl(1090.8, 100%, 50%), 5px 203px hsl(1096.2, 100%, 50%), 7px 204px hsl(1101.6, 100%, 50%), 9px 205px hsl(1107, 100%, 50%), 11px 206px hsl(1112.4, 100%, 50%), 13px 207px hsl(1117.8, 100%, 50%), 14px 208px hsl(1123.2, 100%, 50%), 16px 209px hsl(1128.6, 100%, 50%), 18px 210px hsl(1134, 100%, 50%), 20px 211px hsl(1139.4, 100%, 50%), 22px 212px hsl(1144.8, 100%, 50%), 23px 213px hsl(1150.2, 100%, 50%), 25px 214px hsl(1155.6, 100%, 50%), 27px 215px hsl(1161, 100%, 50%), 28px 216px hsl(1166.4, 100%, 50%), 30px 217px hsl(1171.8, 100%, 50%), 32px 218px hsl(1177.2, 100%, 50%), 33px 219px hsl(1182.6, 100%, 50%), 35px 220px hsl(1188, 100%, 50%), 36px 221px hsl(1193.4, 100%, 50%), 38px 222px hsl(1198.8, 100%, 50%), 39px 223px hsl(1204.2, 100%, 50%), 41px 224px hsl(1209.6, 100%, 50%), 42px 225px hsl(1215, 100%, 50%), 43px 226px hsl(1220.4, 100%, 50%), 45px 227px hsl(1225.8, 100%, 50%), 46px 228px hsl(1231.2, 100%, 50%), 47px 229px hsl(1236.6, 100%, 50%), 48px 230px hsl(1242, 100%, 50%), 49px 231px hsl(1247.4, 100%, 50%), 50px 232px hsl(1252.8, 100%, 50%), 51px 233px hsl(1258.2, 100%, 50%), 52px 234px hsl(1263.6, 100%, 50%), 53px 235px hsl(1269, 100%, 50%), 54px 236px hsl(1274.4, 100%, 50%), 55px 237px hsl(1279.8, 100%, 50%), 55px 238px hsl(1285.2, 100%, 50%), 56px 239px hsl(1290.6, 100%, 50%), 57px 240px hsl(1296, 100%, 50%), 57px 241px hsl(1301.4, 100%, 50%), 58px 242px hsl(1306.8, 100%, 50%), 58px 243px hsl(1312.2, 100%, 50%), 58px 244px hsl(1317.6, 100%, 50%), 59px 245px hsl(1323, 100%, 50%), 59px 246px hsl(1328.4, 100%, 50%), 59px 247px hsl(1333.8, 100%, 50%), 59px 248px hsl(1339.2, 100%, 50%), 59px 249px hsl(1344.6, 100%, 50%), 60px 250px hsl(1350, 100%, 50%), 59px 251px hsl(1355.4, 100%, 50%), 59px 252px hsl(1360.8, 100%, 50%), 59px 253px hsl(1366.2, 100%, 50%), 59px 254px hsl(1371.6, 100%, 50%), 59px 255px hsl(1377, 100%, 50%), 58px 256px hsl(1382.4, 100%, 50%), 58px 257px hsl(1387.8, 100%, 50%), 58px 258px hsl(1393.2, 100%, 50%), 57px 259px hsl(1398.6, 100%, 50%), 57px 260px hsl(1404, 100%, 50%), 56px 261px hsl(1409.4, 100%, 50%), 55px 262px hsl(1414.8, 100%, 50%), 55px 263px hsl(1420.2, 100%, 50%), 54px 264px hsl(1425.6, 100%, 50%), 53px 265px hsl(1431, 100%, 50%), 52px 266px hsl(1436.4, 100%, 50%), 51px 267px hsl(1441.8, 100%, 50%), 50px 268px hsl(1447.2, 100%, 50%), 49px 269px hsl(1452.6, 100%, 50%), 48px 270px hsl(1458, 100%, 50%), 47px 271px hsl(1463.4, 100%, 50%), 46px 272px hsl(1468.8, 100%, 50%), 45px 273px hsl(1474.2, 100%, 50%), 43px 274px hsl(1479.6, 100%, 50%), 42px 275px hsl(1485, 100%, 50%), 41px 276px hsl(1490.4, 100%, 50%), 39px 277px hsl(1495.8, 100%, 50%), 38px 278px hsl(1501.2, 100%, 50%), 36px 279px hsl(1506.6, 100%, 50%), 35px 280px hsl(1512, 100%, 50%), 33px 281px hsl(1517.4, 100%, 50%), 32px 282px hsl(1522.8, 100%, 50%), 30px 283px hsl(1528.2, 100%, 50%), 28px 284px hsl(1533.6, 100%, 50%), 27px 285px hsl(1539, 100%, 50%), 25px 286px hsl(1544.4, 100%, 50%), 23px 287px hsl(1549.8, 100%, 50%), 22px 288px hsl(1555.2, 100%, 50%), 20px 289px hsl(1560.6, 100%, 50%), 18px 290px hsl(1566, 100%, 50%), 16px 291px hsl(1571.4, 100%, 50%), 14px 292px hsl(1576.8, 100%, 50%), 13px 293px hsl(1582.2, 100%, 50%), 11px 294px hsl(1587.6, 100%, 50%), 9px 295px hsl(1593, 100%, 50%), 7px 296px hsl(1598.4, 100%, 50%), 5px 297px hsl(1603.8, 100%, 50%), 3px 298px hsl(1609.2, 100%, 50%), 1px 299px hsl(1614.6, 100%, 50%), 2px 300px hsl(1620, 100%, 50%), -1px 301px hsl(1625.4, 100%, 50%), -3px 302px hsl(1630.8, 100%, 50%), -5px 303px hsl(1636.2, 100%, 50%), -7px 304px hsl(1641.6, 100%, 50%), -9px 305px hsl(1647, 100%, 50%), -11px 306px hsl(1652.4, 100%, 50%), -13px 307px hsl(1657.8, 100%, 50%), -14px 308px hsl(1663.2, 100%, 50%), -16px 309px hsl(1668.6, 100%, 50%), -18px 310px hsl(1674, 100%, 50%), -20px 311px hsl(1679.4, 100%, 50%), -22px 312px hsl(1684.8, 100%, 50%), -23px 313px hsl(1690.2, 100%, 50%), -25px 314px hsl(1695.6, 100%, 50%), -27px 315px hsl(1701, 100%, 50%), -28px 316px hsl(1706.4, 100%, 50%), -30px 317px hsl(1711.8, 100%, 50%), -32px 318px hsl(1717.2, 100%, 50%), -33px 319px hsl(1722.6, 100%, 50%), -35px 320px hsl(1728, 100%, 50%), -36px 321px hsl(1733.4, 100%, 50%), -38px 322px hsl(1738.8, 100%, 50%), -39px 323px hsl(1744.2, 100%, 50%), -41px 324px hsl(1749.6, 100%, 50%), -42px 325px hsl(1755, 100%, 50%), -43px 326px hsl(1760.4, 100%, 50%), -45px 327px hsl(1765.8, 100%, 50%), -46px 328px hsl(1771.2, 100%, 50%), -47px 329px hsl(1776.6, 100%, 50%), -48px 330px hsl(1782, 100%, 50%), -49px 331px hsl(1787.4, 100%, 50%), -50px 332px hsl(1792.8, 100%, 50%), -51px 333px hsl(1798.2, 100%, 50%), -52px 334px hsl(1803.6, 100%, 50%), -53px 335px hsl(1809, 100%, 50%), -54px 336px hsl(1814.4, 100%, 50%), -55px 337px hsl(1819.8, 100%, 50%), -55px 338px hsl(1825.2, 100%, 50%), -56px 339px hsl(1830.6, 100%, 50%), -57px 340px hsl(1836, 100%, 50%), -57px 341px hsl(1841.4, 100%, 50%), -58px 342px hsl(1846.8, 100%, 50%), -58px 343px hsl(1852.2, 100%, 50%), -58px 344px hsl(1857.6, 100%, 50%), -59px 345px hsl(1863, 100%, 50%), -59px 346px hsl(1868.4, 100%, 50%), -59px 347px hsl(1873.8, 100%, 50%), -59px 348px hsl(1879.2, 100%, 50%), -59px 349px hsl(1884.6, 100%, 50%), -60px 350px hsl(1890, 100%, 50%), -59px 351px hsl(1895.4, 100%, 50%), -59px 352px hsl(1900.8, 100%, 50%), -59px 353px hsl(1906.2, 100%, 50%), -59px 354px hsl(1911.6, 100%, 50%), -59px 355px hsl(1917, 100%, 50%), -58px 356px hsl(1922.4, 100%, 50%), -58px 357px hsl(1927.8, 100%, 50%), -58px 358px hsl(1933.2, 100%, 50%), -57px 359px hsl(1938.6, 100%, 50%), -57px 360px hsl(1944, 100%, 50%), -56px 361px hsl(1949.4, 100%, 50%), -55px 362px hsl(1954.8, 100%, 50%), -55px 363px hsl(1960.2, 100%, 50%), -54px 364px hsl(1965.6, 100%, 50%), -53px 365px hsl(1971, 100%, 50%), -52px 366px hsl(1976.4, 100%, 50%), -51px 367px hsl(1981.8, 100%, 50%), -50px 368px hsl(1987.2, 100%, 50%), -49px 369px hsl(1992.6, 100%, 50%), -48px 370px hsl(1998, 100%, 50%), -47px 371px hsl(2003.4, 100%, 50%), -46px 372px hsl(2008.8, 100%, 50%), -45px 373px hsl(2014.2, 100%, 50%), -43px 374px hsl(2019.6, 100%, 50%), -42px 375px hsl(2025, 100%, 50%), -41px 376px hsl(2030.4, 100%, 50%), -39px 377px hsl(2035.8, 100%, 50%), -38px 378px hsl(2041.2, 100%, 50%), -36px 379px hsl(2046.6, 100%, 50%), -35px 380px hsl(2052, 100%, 50%), -33px 381px hsl(2057.4, 100%, 50%), -32px 382px hsl(2062.8, 100%, 50%), -30px 383px hsl(2068.2, 100%, 50%), -28px 384px hsl(2073.6, 100%, 50%), -27px 385px hsl(2079, 100%, 50%), -25px 386px hsl(2084.4, 100%, 50%), -23px 387px hsl(2089.8, 100%, 50%), -22px 388px hsl(2095.2, 100%, 50%), -20px 389px hsl(2100.6, 100%, 50%), -18px 390px hsl(2106, 100%, 50%), -16px 391px hsl(2111.4, 100%, 50%), -14px 392px hsl(2116.8, 100%, 50%), -13px 393px hsl(2122.2, 100%, 50%), -11px 394px hsl(2127.6, 100%, 50%), -9px 395px hsl(2133, 100%, 50%), -7px 396px hsl(2138.4, 100%, 50%), -5px 397px hsl(2143.8, 100%, 50%), -3px 398px hsl(2149.2, 100%, 50%), -1px 399px hsl(2154.6, 100%, 50%); font-size: 40px;";

console.log("%cExample %s", css, 'all code runs happy');

enter image description here

Strike answered 30/1, 2014 at 13:1 Comment(8)
the sadness is that the text somehow doesn't look exactly like your example (at me or in recent chromes, idk)Clay
on my console it gets clipped on overflowing the line's height (Chrome 69, WIN7)I
@Clay Just write a big enough text for the console to wrap it and you will see. :DHarwill
Can this make some performance issue when its length is extremely long?Filature
L.M.A.O This is getting insane!!Parasite
To give it more breathing space treat it like a div and modify the second line to: console.log("%cExample %s", "padding: 0 64px 44px 0; " + css, 'all code runs happy'); The whole 'picture' is ~400 px, to see it all, change 44px to 400px :)Crustaceous
I'm going to imagine that you wrote that CSS by hand because it makes this answer even more epic.Jamshid
Add padding-bottom:400px; to the beginning of the css to see the full effect. (should be a full 6 cycles of rainbow)Norvol
B
109

You can use a custom stylesheet to color your debugger. You can put this code in %localappdata%\Google\Chrome\User Data\Default\User StyleSheets\Custom.css
(For Windows XP, use C:\Documents and Settings<User Name>\Local Settings\Application Data\Google\Chrome\User Data\Default\User StyleSheets\Custom.css) if you are in WinXP, but the directory varies by OS.

.console-error-level .console-message-text{
    color: red;
}

.console-warning-level .console-message-text {
    color: orange;
}

.console-log-level .console-message-text {
    color:green;
}
Bandbox answered 21/9, 2011 at 19:58 Comment(6)
on Ubuntu 10.10, the stylesheet is at ~/.config/google-chrome/Default/User\ StyleSheets/Custom.cssCastilian
on Mac OS X it's at ~/Library/Application\ Support/Google/Chrome/Default/User\ StyleSheets/Custom.css.Byyourleave
The Windows 7 location appears to be `C:\Users\<User Name>\AppData\Local\Google\Chrome\User Data\Default\User StyleSheets`. Also, there's a Solarized Color Scheme Stylesheet for it.Torras
I wanted to style the entire line, not just the text, so I remove the .console-message-text class. Also, the most pleasing background colors I found were #ffece6 for errors, #fafad2 for warnings, and #f0f9ff for normal.Cauthen
Keep in mind this stylesheet applies to all pages that you visit in Chrome, so if you remove a class to decrease the specificity, you may find a website using your styles on a message popup or something like that.Firestone
Custom user stylesheets (Custom.css) no longer work on OSX.Recently
P
92

Older versions of Chrome do not allow you to get console.log()s to show in a specific color programmatically, but calling console.error() will put a red X icon on error lines and make the text red, and console.warn() gets you a yellow ! icon.

You can then filter console entries with the All, Errors, Warnings, and Logs buttons beneath the console.


It turns out Firebug has supported custom CSS for console.logs since 2010 and Chrome support has been added as of Chrome 24.

console.log('%c Oh my heavens! ', 'background: #222; color: #bada55',
            'more text');

When %c appears anywhere in the first argument, the next argument is used as the CSS to style the console line. Further arguments are concatenated (as has always been the case).

Plebiscite answered 21/9, 2011 at 19:39 Comment(2)
Does it have to be the first argument? This code wont work...return console.log("%s", message, "%c%s", "color:#BBBBBB", get_type(message));Oboe
"When %c appears anywhere in the first argument, the next argument is used as the CSS to style the console line" Correction "When %c appears anywhere in any argument, the next argument is used as the CSS to style the the console line output following the %c. e.g. i.imgur.com/msfPNbK.pngPattison
Y
54

I wrote template-colors-web https://github.com/icodeforlove/Console.js to allow us to do this a bit easier

console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red);

The above would be extremely hard to do with the default console.log.

For a live interactive demo click here.

enter image description here

Yardage answered 27/4, 2014 at 7:53 Comment(7)
Unlike most of the other solutions, this allows for coloring string-containing variables as well.Hofuf
Actually this is not really supported for example you cant currently do this console.log(`this is inline ${'red'.red.bold} and this is more text`.grey) the styling would stop after the first styled itemYardage
Even though there's no "inline" coloring it's still possible to do things like var txt = "asd"; txt.red or `${txt}`.red + `${txt}`.green. I'm not aware of a way to do this with the %c syntax others are recommending. So thanks for building the libraryHofuf
How do you detect support for this feature in a browser, I looked at the code for your library and couldn't spot it? #40428739Ostia
@MuhammadRehanSaeed Browser detectionYardage
this console.warn('Error: this is an error message'.error); should probably read console.warn('Error: this is an error message', error); notice the comma instead of dot, or am I missing something?Crenulation
@Can You're missing something. He's extending the String prorotype with custom getters that style the console output, so string.error is in fact correct there.Marchioness
G
53

I actually just found this by accident being curious with what would happen but you can actually use bash colouring flags to set the colour of an output in Chrome:

console.log('\x1b[36m Hello \x1b[34m Colored \x1b[35m World!');
console.log('\x1B[31mHello\x1B[34m World');
console.log('\x1b[43mHighlighted');

Output:

Hello World red and blue

enter image description here

See this link for how colour flags work: https://misc.flogisoft.com/bash/tip_colors_and_formatting

Basically use the \x1b or \x1B in place of \e. eg. \x1b[31m and all text after that will be switched to the new colour.

I haven't tried this in any other browser though, but thought it worth mentioning.

Gev answered 10/10, 2018 at 6:12 Comment(4)
This is cool but seems to be chrome/chromium specific. I tested it in firefox 65 it doesn't workCesura
Yeah Firefox also warns you about pasting into the console. For Firefox you'll have to use the %c and styles.Gev
Why this colorization only works in first argument? I.e. this won't work console.log('\x1b[36m Hello', '\x1b[34m Colored', '\x1b[35m World!');Waffle
Firefox still doesn't support this :(Laager
E
46

Update:

I have written a JavaScript library last year for myself. It contains other features e.g verbosity for debug logs and also provides a download logs method that exports a log file. Have a look at the JS Logger library and its documentation.


I know It's a bit late to answer but as the OP asked to get custom color messages in console for different options. Everyone is passing the color style property in each console.log() statement which confuses the reader by creating complexity in the code and also harm the overall look & feel of the code.

What I suggest is to write a function with few predetermined colors (e.g success, error, info, warning, default colors) which will be applied on the basis of the parameter passed to the function.

It improves the readability and reduces the complexity in the code. It is too easy to maintain and further extend according to your needs.


Given below is a JavaScript function that you have to write once and than use it again and again.

function colorLog(message, color) {

    color = color || "black";

    switch (color) {
        case "success":  
             color = "Green"; 
             break;
        case "info":     
                color = "DodgerBlue";  
             break;
        case "error":   
             color = "Red";     
             break;
        case "warning":  
             color = "Orange";   
             break;
        default: 
             color = color;
    }

    console.log("%c" + message, "color:" + color);
}

Output:

enter image description here


The default color is black and you don't have to pass any keyword as parameter in that case. In other cases, you should pass success, error, warning, or info keywords for desired results.

Here is working JSFiddle. See output in the browser's console.

Edgardoedge answered 2/3, 2017 at 9:48 Comment(4)
I had in mind an implementation that was more log.info("this would be green"), etc. Close enough.Butch
Cool, but consider that standard approach with console.error(), console.warn(), console.info() seems better in this scenario, as it also 1) provides semantics that we lose here, which allows to filter messages by severity in console 2) use colors that is best for user's configuration, eg. browser in dark mode, or high contrast modeJarvisjary
console.info() and console.log() shows the same standard log and you can't differentiate with only looking at the output. But yeah console.warn() and console.error() can be used to filter messages later on. As the OP asked; how to print color logs in console. I think the answer is best according to the question asked by the OP. We are not filtering messages but we are focusing on printing color logs. I really do appreciate your suggestion and the example can be enhanced further to meet your requirements as well.Edgardoedge
@SuhaibJanjua How to do that but keeping the good row number reference from the inspector?Valeric
T
43

Emoji

You can use colors for text as others mentioned in their answers to have colorful text with a background or foreground color.

But you can use emojis instead! for example, you can use⚠️ for warning messages and 🛑 for error messages.

Or simply use these notebooks as a color:

console.log('📕: error message');
console.log('📙: warning message');
console.log('📗: ok status message');
console.log('📘: action message');
console.log('📓: canceled status message');
console.log('📔: Or anything you like and want to recognize immediately by color');

🎁 Bonus:

This method also helps you to quickly scan and find logs directly in the source code.

But some Linux distribution default emoji font is not colorful by default and you may want to make them colorful, first.


How to open emoji panel?

mac os: control + command + space

windows: win + .

linux: control + . or control + ;

Thoracotomy answered 10/10, 2020 at 9:12 Comment(4)
what do you type to display these? ⚠️ 🛑 ( I copied them from your answer )Benzaldehyde
Depends on the OS and many other things. In macOS, Emoji & SymbolsThoracotomy
In windows you can use Win + dot to type emoji.Friedrick
if you are not able to get a way to type (eg. linux minimal install), just google for emoji and copy it from there.....Sandblind
M
32
colors = {
    reset: '\033[0m',

    //text color

    black: '\033[30m',
    red: '\033[31m',
    green: '\033[32m',
    yellow: '\033[33m',
    blue: '\033[34m',
    magenta: '\033[35m',
    cyan: '\033[36m',
    white: '\033[37m',

    //background color

    blackBg: '\033[40m',
    redBg: '\033[41m',
    greenBg: '\033[42m',
    yellowBg: '\033[43m',
    blueBg: '\033[44m',
    magentaBg: '\033[45m',
    cyanBg: '\033[46m',
    whiteBg: '\033[47m'
}

console.log('\033[31m this is red color on text');
console.log('\033[0m this is reset');
console.log('\033[41m this is red color on background');
Margarettmargaretta answered 1/3, 2016 at 5:47 Comment(6)
Or console.log(color.red+' this is red color on text'); as colors.red already assigned.Gamber
Doesn't do anything on Chrome and Safari.Lodovico
@Lodovico It's not in the answer, but that's for Node.js.Idolism
Yeah I was confused for a minute half-impressed that Chrome was supporting escape sequencesDaydream
@Daydream - it works (Chrome 69 here). you can resume your previous half-impressed state ;)I
Note that in strict mode, you've to replace \033 with \x1b or \u001b as it doesn't support numeric escapes.Heathenish
M
28

There are a series of inbuilt functions for coloring the console log:

//For pink background and red text
console.error("Hello World");  

//For yellow background and brown text
console.warn("Hello World");  

//For just a INFO symbol at the beginning of the text
console.info("Hello World");  

//for custom colored text
console.log('%cHello World','color:blue');
//here blue could be replaced by any color code

//for custom colored text with custom background text
console.log('%cHello World','background:red;color:#fff')
Metamorphose answered 22/2, 2016 at 9:30 Comment(3)
it seems that console.info() no longer adds the info icon.. not sure when this happened. It's now no different than console.log() (at least on Chrome and Firefox)Churlish
Years ago console.info() used to output a line in blue. Then one day, it was removed. Today, it uses default black. It no longer has built-in coloring.Hako
note that styling can also be added to warn and error: console.error("%cblue","color:blue")Blockbusting
A
28

Yes just add %c sign before your message and the style followed by your message.

console.log('%c Hello World','color:red;border:1px solid dodgerblue');

If you are using node and want to color console in terminal then you can use escape sequences like

console.log('\x1b[33m%s\x1b[0m', 'hi!') 

will color console yellow, else you can use libraries like chalk to color console

const chalk = require('chalk') 
console.log(chalk.yellow('hi!')) 
Aeronautics answered 14/7, 2021 at 6:28 Comment(1)
The question is about Chrome Developer Console. Chalk doesn't work on Chrome Developer Console.Defendant
J
19

Google has documented this https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css

The CSS format specifier allows you to customize the display in the console. Start the string with the specifier and give the style you wish to apply as the second parameter.

One example:

console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");
Jehiah answered 9/6, 2015 at 3:43 Comment(3)
"Google has documented this developer.chrome.com/devtools/docs/…." There's now no mention of console styling there.Pattison
It is here developers.google.com/web/tools/chrome-devtools/console/…Pattison
Aaand now it's here: developer.chrome.com/docs/devtools/console/format-styleAncalin
D
17

You can try:

console.log("%cI am red %cI am green", "color: red", "color: green");

The output:

enter image description here

Dorothadorothea answered 1/10, 2020 at 1:18 Comment(1)
this looks like it works, but your image is wrong tho. also there are milions answer like your in this post ^^Jerky
N
16

I've discovered that you can make logs with colors using ANSI color codes, what makes easier to find specific messages in debug. Try it:

console.log( "\u001b[1;31m Red message" );
console.log( "\u001b[1;32m Green message" );
console.log( "\u001b[1;33m Yellow message" );
console.log( "\u001b[1;34m Blue message" );
console.log( "\u001b[1;35m Purple message" );
console.log( "\u001b[1;36m Cyan message" );
Nuss answered 29/1, 2021 at 15:44 Comment(2)
In my terminal for some reason, after adding one of your examples, it doesn't color that specific log but ALL logs after that regardless if I am using the same coloring or not.Prefix
@Geroge Linardis: Adding "\x1b[0m" will end the coloring as shown the following post: https://mcmap.net/q/45517/-colors-in-javascript-console For example, printing a green message could be done as follows: console.log("\u001b[1;32mGreen message\x1b[0m");Poorly
F
15

template system, useful if you want to create colorful line text without creating full style for every block

var tpl = 'background-color:greenyellow; border:3px solid orange; font-size:18px; font-weight: bold;padding:3px 5px;color:';
console.log('%cMagenta %cRed %cBlue', `${tpl} magenta`, `${tpl} Red`,`${tpl} #4274fb`);

colorful console log

Fleawort answered 18/6, 2017 at 5:37 Comment(0)
R
9

Check this out:

Animation in console, plus CSS

(function() {
  var frame = 0;
  var frames = [
    "This",
    "is",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!"
  ];
  var showNext = () => {
    console.clear();
    console.log(
      `%c `,
      "background: red; color: white; font-size: 15px; padding: 3px 41%;"
    );
    console.log(
      `%c ${frames[frame]}`,
      "background: red; color: white; font-size: 25px; padding: 3px 40%;"
    );
    console.log(
      `%c `,
      "background: red; color: white; font-size: 15px; padding: 3px 41%;"
    );
    setTimeout(
      showNext,
      frames[frame] === "SPARTA!" || frames[frame] === " " ? 100 : 1500
    );
    // next frame and loop
    frame++;
    if (frame >= frames.length) {
      frame = 0;
    }
  };
  showNext();
})();

https://jsfiddle.net/a8y3jhfL/

you can paste ASCII in each frame to watch an ASCII animation

Risa answered 15/2, 2018 at 16:47 Comment(1)
It's very simple but it turned out really well! LOLSo
A
9

I doubt that anyone will actually see it but I have a simple solution for those who want to mix several colors in the same line:

export enum Colors {
    Black = '\033[30m',
    Red = '\x1b[31m',
    Green = '\x1b[32m',
    Yellow = '\x1b[33m',
    Blue = '\033[34m',
    Magenta = '\033[35m',
    Cyan = '\033[36m',
    White = '\033[37m'
}


function color(text: string, color: color: Colors) {
    return `${color}${text}\x1b[0m`;
}


console.log(`This is ${color('green text', Colors.Green)} but this is black. This is red ${color('red', Colors.Red)} etc`);
Assessment answered 9/3, 2020 at 14:11 Comment(1)
I saw it, thanks! And here's a link that will give you even more goodies like that: Make Console.log() output colorful....Borosilicate
K
8

If you want to be modern you can also use template literals here is a simple and complex example; Template literals let you use emojis, vars and way more cool stuff 😎

Simple

enter image description here

Complex

enter image description here

Code

/*
* Simple example
*/

console.log(
  `%c[line 42] | fooBar.js myFunc() -> YOU DEBUG MESSAGE HERE `,
  ` color:white; background-color:black; border-left: 1px solid yellow; padding: 4px;`
);

/*
* Complex example
*/

const path = `../this/goes/to/my/dir`;

const line = 42;

const ref = `myFunc()`;

const message = `A FANCY DEBUG MESSAGE 💎💎💎 `;

const styling = `
    color:white;
    background-color:black;
    border-left: 1px solid yellow;
    padding: 8px;
    font-weight: 600;
    font-family: Courier;
`;

console.log(
    `%c ✨ F A N C Y - L O G G E R ✨`,
    `${styling} font-size: 16px; border-top: 1px solid yellow;`
);

console.log(
    `%c  Path: ${path} `,
    `${styling} font-size: 10px; font-weight: 100;`
);

console.log(
    `%c  Line: ${line}`,
    `${styling} font-size: 10px; font-weight: 100;`
);

console.log(
    `%c  Ref: ${ref} `,
    `${styling} font-size: 10px; font-weight: 100;`
);

console.log(
  `%c  Message: ${message} `,
  `${styling} font-size: 12px; border-bottom: 1px solid yellow;`
);
Keith answered 7/6, 2021 at 23:13 Comment(0)
I
6

To chain CSS3 styles which spans across multiple lines, you can do like this,

var styles = [
    'background: linear-gradient(#D33106, #571402)'
    , 'border: 1px solid #3E0E02'
    , 'color: white'
    , 'display: block'
    , 'text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)'
    , 'box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset'
    , 'line-height: 40px'
    , 'text-align: center'
    , 'font-weight: bold'
].join(';');

console.log('%c a spicy log message ?', styles);

Result

enter image description here

Find more :- https://coderwall.com/p/fskzdw/colorful-console-log

Cheers.

Impersonality answered 18/2, 2019 at 9:14 Comment(0)
I
6

By default, there are few inbuilt console methods to display warnings, errors and normal console along with the specific icons and text colors.

console.log('console.log');
console.warn('console.warn');
console.error('console.error');

But If you still want to apply your own styles, You can use %c with the message and CSS style rules as a second parameter.

console.log('%cconsole.log', 'color: green;');
console.warn('%cconsole.warn', 'color: green;');
console.error('%cconsole.error', 'color: green;');

Note : While running the above code snippets, Kindly check the results in the browser console instead of snippet results.

Indistinct answered 6/6, 2022 at 7:26 Comment(0)
D
5

from Chrome 60, they removed the facility of blue text color while writing console.info and does many much changes in console API.

if you write a string literal in the es6 pattern, using the backticks `` as the identifier (called as template string ) in console.log() then below way can colorize the console output.

console.log(`%cToday date=>%c${new Date()}`,`color:#F74C2F`, `color:green`);
// output :Today date (in red color) => Date (in green color)
Dneprodzerzhinsk answered 28/9, 2017 at 17:1 Comment(0)
S
4

OPTION 1

// log-css.js v2
const log = console.log.bind()
const css = (text, options) => {
    let cssOptions = ''
    for (let prop in options) {
        const value = options[prop]
        prop = camelCaseToDashCase(prop)
        cssOptions += `${prop}: ${value}; `
    }
    return [`%c${text}`, cssOptions.trim()]

    function camelCaseToDashCase(value) {
        return value.replace(/[A-Z]/g, matched => `-${matched.toLowerCase()}`)
    }
}

Example:

log(...css('Example =P', {
    backgroundColor: 'blue',
    color: 'white',
    // fontFamily: 'Consolas',
    fontSize: '25px',
    fontWeight: '700',
    // lineHeight: '25px',
    padding: '7px 7px'
}))

OPTION 2

I create now the log-css.js https://codepen.io/luis7lobo9b/pen/QWyobwY

// log-css.js v1
const log = console.log.bind();
const css = function(item, color = '#fff', background = 'none', fontSize = '12px', fontWeight = 700, fontFamily) {
    return ['%c ' + item + ' ', 'color:' + color + ';background:' + background + ';font-size:' + fontSize + ';font-weight:' + fontWeight + (fontFamily ? ';font-family:' + fontFamily : '')];
};

Example:

log(...css('Lorem ipsum dolor sit amet, consectetur adipisicing elit.', 'rebeccapurple', '#000', '14px'));
So answered 23/7, 2020 at 13:17 Comment(0)
L
3

I recently wanted to solve for a similar issue and constructed a small function to color only keywords i cared about which were easily identifiable by surrounding curly braces {keyword}.

This worked like a charm:

var text = 'some text with some {special} formatting on this {keyword} and this {keyword}'
var splitText = text.split(' ');
var cssRules = [];
var styledText = '';
_.each(splitText, (split) => {
    if (/^\{/.test(split)) {
        cssRules.push('color:blue');
    } else {
        cssRules.push('color:inherit')
    }
    styledText += `%c${split} `
});
console.log(styledText , ...cssRules)

enter image description here

technically you could swap out the if statement with a switch/case statement to allow multiple stylings for different reasons

Larentia answered 27/5, 2018 at 6:10 Comment(0)
S
3

I wrote a reallllllllllllllllly simple plugin for myself several years ago:

To add to your page all you need to do is put this in the head:

<script src="https://jackcrane.github.io/static/cdn/jconsole.js" type="text/javascript">

Then in JS:

jconsole.color.red.log('hellllooo world');

The framework has code for:

jconsole.color.red.log();
jconsole.color.orange.log();
jconsole.color.yellow.log();
jconsole.color.green.log();
jconsole.color.blue.log();
jconsole.color.purple.log();
jconsole.color.teal.log();

as well as:

jconsole.css.log("hello world","color:red;");

for any other css. The above is designed with the following syntax:

jconsole.css.log(message to log,css code to style the logged message)
Serra answered 12/9, 2019 at 19:33 Comment(0)
U
2

I created a package for the same. cslog

screenshow

Install it with

npm i cslog

Use It like this

import log from 'cslog'

log.h2("This is heading 2")
log.p("This is colored paragraph")
log.d(person, "Person Info")

You can give your custom colors as well. here

Umiak answered 15/9, 2020 at 6:51 Comment(0)
H
2

Here's another approach (in Typescript), which overrides the console.log function and inspects the message passed in order to apply CSS formatting depending on a beginning token in the message. A benefit of this method is the callee's don't need to use some wrapper console.log function, they can stick to using vanilla console.log() and so if this override ever goes away the functionality will just revert to the default console.log:

// An example of disabling logging depending on environment:
const isLoggingEnabled = process.env.NODE_ENV !== 'production';

// Store the original logging function so we can trigger it later
const originalConsoleLog = console.log;

// Override logging to perform our own logic
console.log = (args: any) => {
    if (!isLoggingEnabled) {
        return;
    }

    // Define some tokens and their corresponding CSS
    const parsing = [
        {
            token: '[SUCCESS]',
            css: 'color: green; font-weight: bold;',
        },
        {
            token: '[ERROR]',
            css: 'color: red; font-weight: bold;',
        },
        {
            token: '[WARN]',
            css: 'color: orange; font-weight: bold;',
        },
        {
            token: '[DEBUG]',
            css: 'color: blue;',
        },
    ];

    // Currently only supports console.log(...) with a single string argument. 
    if (typeof args === 'string') {
        const message: string = args;
        let formattedArgs: string[] = [];
        for (let i = 0; i < parsing.length; i += 1) {
            const parser = parsing[i];
            if (args.startsWith(parser.token)) {
                formattedArgs = [`%c${message.substring(parser.token.length + 1, message.length)}`, parser.css];
                break;
            }
        }
        originalConsoleLog.apply(console, formattedArgs);
    } else {
        originalConsoleLog.apply(console, args);
    }
};

Example usage:

console.log('[ERROR] Something went wrong!');

Output:

Output Of Log

Hypoderm answered 25/1, 2022 at 16:31 Comment(2)
Looses the calling context and shows the line where the apply happens and not the originating line of codeFasciate
I see that is the best answer for best handling console logging. ThanksMurder
N
2

The simple way (that I've found) for marked the console log is:

console.log("%c %s", "background-color:yellow; color: black", 'foo');

result:

enter image description here

Nolte answered 31/5, 2023 at 12:54 Comment(0)
M
1

I wrote a npm module that gives one the possibility to pass:

  • Custom colors - to both text and background;
  • Prefixes - to help identify the source, like [MyFunction]
  • Types - like warning, success, info and other predefined message types

https://www.npmjs.com/package/console-log-plus

Output (with custom prefixes):

enter image description here

clp({
  type: 'ok',
  prefix: 'Okay',
  message: 'you bet'
});
clp({
  type: 'error',
  prefix: 'Ouch',
  message: 'you bet'
});
clp({
  type: 'warning',
  prefix: 'I told you',
  message: 'you bet'
});
clp({
  type: 'attention',
  prefix: 'Watch it!',
  message: 'you bet'
});
clp({
  type: 'success',
  prefix: 'Awesome!',
  message: 'you bet'
});
clp({
  type: 'info',
  prefix: 'FYI',
  message: 'you bet'
});
clp({
  type: 'default',
  prefix: 'No fun',
  message: 'you bet'
});

Output (without custom prefixes):

enter image description here

Input:

clp({
  type: 'ok',
  message: 'you bet'
});
clp({
  type: 'error',
  message: 'you bet'
});
clp({
  type: 'warning',
  message: 'you bet'
});
clp({
  type: 'attention',
  message: 'you bet'
});
clp({
  type: 'success',
  message: 'you bet'
});
clp({
  type: 'info',
  message: 'you bet'
});
clp({
  type: 'default',
  message: 'you bet'
});

To make sure the user won't render an invalid color, I wrote a color validator as well. It will validate colors by name, hex, rgb, rgba, hsl or hsla values

Motorcar answered 11/6, 2019 at 19:54 Comment(0)
P
1

const coloring = fn => ({ background, color = 'white' }) => (...text) => fn(`%c${text.join('')}`, `color:${color};background:${background}`);
const colors = {
  primary: '#007bff',
  success: '#28a745',
  warning: '#ffc107',
  danger: '#dc3545',
  info: '#17a2b8',
};
const dir = (key = '', value = {}) => {
  logs.primary(`++++++++++++start:${key}++++++++++++++`);
  console.dir(value);
  logs.primary(`++++++++++++end:${key}++++++++++++++`);
};
const logs = Object.keys(colors)
  .reduce((prev, curr) => ({ ...prev, [curr]: coloring(console.log)({ background: colors[curr] }) }), { dir });
  
  logs.success('hello succes');
  logs.warning('hello fail');
Portraiture answered 23/9, 2020 at 7:27 Comment(0)
D
-4

If you want to color your terminal console, then you can use npm package chalk

npm i chalk

enter image description here

Downer answered 1/10, 2020 at 8:0 Comment(1)
the question was about a browser solutionBeelzebub

© 2022 - 2024 — McMap. All rights reserved.